collection.each()不会迭代模型

use*_*521 7 backbone.js

我试图迭代由集合提取的模型.

我有一段代码:

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();
}
Run Code Online (Sandbox Code Playgroud)

和结果:

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@gmail.com"
__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
Run Code Online (Sandbox Code Playgroud)

所以fetch方法确实有效 - 在对象转储中,我可以找到4条记录,但迭代集合不起作用......

Cyc*_*one 20

这样做each的集合能够使model自身作为argument.

试试这个:

this.collection.each(function(model){
  console.log(model); 
});
Run Code Online (Sandbox Code Playgroud)

它应该为您model提供当前的迭代.


Das*_*shK 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();
},
Run Code Online (Sandbox Code Playgroud)

处理此问题的另一种方法是在fetch上添加成功处理程序,但我认为在这种情况下,侦听重置事件应该足够了.

希望这可以帮助!

顺便说一下,像Cyclone说的那样,.each的处理程序应该只是一个没有索引的模型.:)