2012-12-04 55 views
0

更新不能在Backbone.js的

通過收集迭代這是一個愚蠢的錯字。我正在使用Backbone.Model.extend進行收藏。 捂臉


試圖通過集合迭代,但我想我已經錯誤地填充了什麼:

RecentContent = Backbone.View.extend 
    initialize: -> 
     @collection = new ContentAPI.ContentCollection() 

     @collection.fetch 
      success: (collection, response, options) => 
       console.log @collection 
       # d {attributes: Object, _escapedAttributes: Object, cid: "c4", changed: Object, _silent: Object…} 
       # property `attributes` contains Objects from server 

       console.log @collection.models # undefined 
       @render() 

    #--------------------- 

    render: -> 
     # ERROR: Object has no method 'each' 
     @collection.each (model) -> 
      console.log model 

我也注意到,如果我試圖reset事件綁定到@collection(而不是從success回調中渲染),它似乎從未被解僱。

收集是非常簡單的:

class ContentAPI 
    @Content: Backbone.Model.extend {} 

    @ContentCollection: Backbone.Model.extend 
     url: "/api/content/" 
     model: @Content 

我有點新幹線所以謝謝你的幫助。 :)

+0

即使找出答案,也應該選擇一個答案。 – Russ

回答

1

問題是您的集合繼承了錯誤的基類。

@ContentCollection: Backbone.Model.extend 

應該

@ContentCollection: Backbone.Collection.extend 
+0

愚蠢的疏忽,謝謝! – bricker

1

我不是CoffeeScript的專家,但我覺得你的問題是

@ContentCollection: Backbone.Model.extend 

應該

@ContentCollection: Backbone.Collection.extend 

而且遍歷的時候你收集的模型,使用

_.each(collection.models, function(model) { console.log(model); }); 
+0

Underscore方法被合併到集合原型上,所以他擁有'each'的方式很好。 – loganfsmyth

+0

我以爲是。雖然我不能在Backbone站點找到文檔。 – TYRONEMICHAEL

+0

您要查找的文檔:http://backbonejs.org/#Collection-Underscore-Methods –