2013-01-04 39 views
4

我是Backbone JS的新手,一直關注着Christopher Coenraets Wine Cellar tutorialBackbone JS - this.model.models而不是this.collection?

這一切工作正常和丹迪,但我不明白他如何使用this.model.models訪問收集而不是this.collection。此外,當我嘗試將代碼更改爲後者時,看起來this.collection未定義。

window.WineListView = Backbone.View.extend({ 

    tagName:'ul', 

    initialize:function() { 
     this.model.bind("reset", this.render, this); 
    }, 

    render:function (eventName) { 
     _.each(this.model.models, function (wine) { 
      $(this.el).append(new WineListItemView({model:wine}).render().el); 
     }, this); 
     return this; 
    } 

}); 
+2

'models'是Collection對象的成員。 Collection被分配給的名稱('model' vs'collection')就像其他變量名一樣,並且與包含的對象類型沒有關係。 –

回答

6

兩件事情引起您的不捨:

  • 你可以注入一個集合在一個視圖不過你想要的。通常的方法是通過一個集合屬性,但在這裏它被作爲路由器的模型傳遞:

    this.wineList = new WineCollection(); 
    this.wineListView = new WineListView({model:this.wineList}); 
    
  • collection.models持有的模型的集合,在原始排列

    模式collection.models
    原始訪問集合中模型的JavaScript數組。 通常您會希望使用get,at或Underscore方法訪問模型對象,但有時需要直接引用數組 。

如果你想在視圖中使用this.collection,您應該修改路由器

this.wineList = new WineCollection(); 
this.wineListView = new WineListView({collection: this.wineList}); 

,然後你可以使用它作爲

window.WineListView = Backbone.View.extend({ 
    tagName: 'ul', 

    initialize: function() { 
     this.collection.bind("reset", this.render, this); 
    }, 

    render: function (eventName) { 
     // Backbone proxies Underscore methods on collections 
     // _.each(this.collection.models, function (wine) { 

     this.collection.each(function (wine) { 
      $(this.el).append(new WineListItemView({model: wine}).render().el); 
     }, this); 

     return this; 
    } 
});