collection.each()不会迭代模型

时间:2013-02-13 12:50:29

标签: 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();
}

和结果:

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

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

2 个答案:

答案 0 :(得分:20)

对集合进行each会将model本身作为argument

试试这个:

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

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

答案 1 :(得分: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();
},

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

希望这有帮助!

BTW,就像Cyclone所说,.each的处理程序应该只是一个没有索引的模型。 :)