2013-02-13 58 views
7

我正在嘗試遍歷集合獲取的模型。collection.each()不遍歷模型

我有如下因素的一段代碼:

initialize: function() { 
       this.collection = new UserCollection(); 
       this.collection.fetch(); 
       this.render(); 
      }, 

      renderCollection: function() { 
       console.log("rendering collection"); 
       this.collection.each(function(index,model){ 
        console.log("model"); 
       }); 
       console.log(this.collection); 
      }, 

render: function() { 
       this.template = _.template(template, {}); 
       this.$el.html(this.template); 
       // some other stuff 
       this.renderCollection(); 
} 

和結果:

rendering collection 

d {models: Array[0], length: 0, _byId: Object, constructor: function, model: function…} 
_byId: Object 
_idAttr: "id" 
length: 4 
models: Array[4] 
0: d 
_changing: false 
_events: Object 
_pending: false 
_previousAttributes: Object 
attributes: Object 
created: "2013-02-13 09:22:42" 
id: "1" 
modified: "2013-02-13 09:22:42" 
role: "admin" 
username: "[email protected]" 
__proto__: Object 
changed: Object 
cid: "c5" 
collection: d 
id: "1" 
__proto__: e 
1: d 
2: d 
3: d 
length: 4 
__proto__: Array[0] 
__proto__: e 
user_list.js:25 

所以取方法做的工作 - 在對象轉儲我能找到4條牽強,但遍歷集合呢不工作...

回答

8

根據您提供的輸出,它看起來不像打印任何「模型」。這可能是由於,執行.each()塊時,this.collection可能尚未完全獲取。這是由於JavaScript的異步性質。

試試這個在您的初始化方法:

initialize: function() { 
    var me = this; 
    this.collection = new UserCollection(); 
    // Listen to 'reset' events from collection, so when .fetch() is completed and all 
    // ready to go, it'll trigger .render() automatically. 
    this.listenTo(this.collection, 'reset', this.render); 
    this.collection.fetch(); 
}, 

另一種方式來處理,這是添加上獲取成功的處理程序,但我覺得聽重置事件應該是在這種情況下就足夠了。

希望這會有所幫助!

順便說一句,像Cyclone說的那樣,.each的處理程序應該只是一個沒有索引的模型。 :)

+1

該問題可能來自服務器輸出,需要是一個有效的json對象數組。即在PHP中索引json_encoded數組 – 2014-03-24 08:48:16

+1

您的迭代器應該是: 'this.collection.each(function(model){...});' 或 'this.collection.each(function(model,index){...});' OP有索引和模型錯誤的方式。 – 2014-04-30 13:46:38

+0

我不得不做每一個collection.models這樣(不是集合):http://stackoverflow.com/questions/11726943/for-loop-over-backbone-collection...這是我的問題。 – Kelly 2014-05-25 15:50:20

19

each收集給model本身作爲argument

試試這個:

this.collection.each(function(model){ 
    console.log(model); 
}); 

它應該給你model當前迭代。