簡體   English   中英

骨干並遍歷一個集合,但結果未附加到$(this.el)

[英]backbone and iterating through a collection but the results are not being appended to $(this.el)

我正在將標准Web應用程序遷移到骨干網,今天是第一天,所以假設我犯了一些真正的初學者錯誤。 我有以下View類需要一個集合。 我正在遍歷它,它返回了它應該基於console.log'ging的內容(被評論為“這行得通”),但是它沒有追加任何內容(被評論為“這行不通”)。 有人能說出這段片段是我做錯了什么嗎?

var HomepagePositionsView = Backbone.View.extend({
    render:function(){
       var str="";
       this.collection.forEach(function(location){
         var hpsView=new HomepagePositionView({model:location});
         //hpView.render();
         console.log(hpsView.render().el); // this works ok
         //str+=hpView.el;
         $(this.el).append(hpsView.render().el);  // this doesn't work

       });
       //$(this.el).text(str);
       console.log(this.el); // just <div></div>
       return this;
    }
  });

感謝任何幫助

編輯#1

這就是我實例化的方式:

homepage_position: function(){
  console.log("within homepage_position");
  this.homepage_positions= new Locations();
  this.homepage_positions.url='/hex-jt/api-homepage-position';
  var str="";
  this.homepage_positions.fetch({success: function(data){
    var hpView= new HomepagePositionsView({ collection:data});
    hpView.render();
    console.log(hpView.el);
    //str+= $.html(hpView.el);
    $('#app').html(hpView.el);
  }});

您可以顯示要初始化新視圖的位置嗎,即:

new HomepagePositionsView({...})

我的猜測是您沒有提供附加的el,因此發生的是您在視圖中正確創建了html,但沒有指定要附加到其上的DOM元素。 為了清楚起見,它應該看起來像這樣:

new HomepagePositionsView({collection: myCollection, el: $('#someElToAttachTo')})

您應該使用this。$ el而不是$(this.el),因為this。$ el是一個緩存的jQuery對象。 另外,如果您的Backbone庫是最新的,則可以執行

this.collection.each(function(){...})

它將委托給underscore.js,后者又委托給最快的選項,具體取決於瀏覽器。 最后,如果您打算對Backbone做任何認真的工作,我會考慮查看Marionette.js,因為它為構建大型js應用程序提供了許多不錯的功能。

當您遍歷集合時, 不再引用您用來引用el的視圖對象。 嘗試將其緩存在循環外,將其分配給self,然后在從渲染的子視圖中追加el時,從self引用el。

var self = this;

this.collection.forEach(function () {
    $(self.el).append(...)
});

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM