2013-02-13 109 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当前迭代。