2011-12-20 112 views
1

剛開始時與骨幹&我對如何從集合中檢索模型有點困惑。給予解釋,我有以下方法路由器:骨幹/ Javascript檢查:不能從集合中抓取模型

index: (date) -> 
    @days = new Demomanager.Collections.DaysCollection(@options) 
    @days.reset @options.days 
    @days.fetch() 
    @view = new Demomanager.Views.Days.IndexView(days: @days) 
    $("#calendar").html(@view.render().el) 

其傳遞到下面的視圖:

class Demomanager.Views.Days.IndexView extends Backbone.View 
    template: JST["backbone/templates/days/index"] 

    initialize: (options) -> 
    _.bindAll(this, 'addOne', 'addAll', 'render') 
    @options.days.bind('reset', @addAll) 
    console.log @options.days 

當我檢查,在瀏覽器在視圖中最後一行(@ options.days)檢查員,它回來DaysCollection,其中包括一個'模型'陣列完成36條目(這是預期的)。

但是,當我改變,而不是與36款的陣列

console.log @options.days 

console.log @options.days.models 

我得到一個空數組。最後,如果我通過控制檯本身(window.router.days.models)訪問同一個對象,它將按照預期顯示36個模型。

因此,簡而言之:發生了什麼事情,以及如何從視圖中訪問這些模型?

非常感謝...

回答

1

你要移到你送到你的觀點:

var IndexView = Backbone.View.extend({ 
    collection: new Demomanager.Collections.DaysCollection(options), 
    template: myTemplate, 

    initialize: function() { 
     $("#calendar").html(_.template(myTemplate, {})); 

     this.collection.fetch(); 
     this.collection.reset(null, options.days); // don't know how coffeescript works, but first arg here is models set not the options object 

     this.collection.bind("add", this.addOne, this); 
    }, 


    addAll: function() { 
     this.collection.each(this.addOne, this); 
    }, 
    addOne: function(model) { 
     $(this.el).append(new ChildView({model: model})); 
    } 

}); 
2

也許它的原因是你進行異步調用。因此,當您在視圖的構造函數中記錄options.days時,數據尚未加載。在days.fetch的成功回調中創建您的視圖會更好。這樣做,您可以在加載失敗時啓動不同的視圖。