collection.each()不迭代模型 [英] collection.each() does not iterate over models

查看:133
本文介绍了collection.each()不迭代模型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想遍历集合所获取的模型。

I am trying to iterate over models fetched by collection.

我已经如下因素一块code的:

I have folowing piece of code:

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

所以取方法没有工作 - 对象转储我能找到4条牵强,但遍历集合不起作用...

So the fetch method did work - in object dump I can find 4 records fetched but iterating over the collection does not work...

推荐答案

根据您所提供,它看起来并不像什么模式已被打印输出。它可能引起,当执行。每()块, this.collection 可能没有被完全取然而。这是由于JavaScript的的异步性。

Based on the output you provided, it doesn't look like any "model" has been printed. It's probably caused by, when the .each() block is executed, this.collection may not have been completely fetched yet. This is due to the async nature of JavaScript.

试试这个在您的初始化方法:

Try this in your initialize method:

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();
},

另一种方式来处理,这是增加对获取成功的处理程序,但我觉得听重置事件应该是在这种情况下就足够了。

The other way to handle this is to add a success handler on fetch, but I think listening to reset events should be sufficient in this case.

希望这有助于!

顺便说一句,像旋风说,对。每个处理程序应该只是没有索引的模式。 :)

BTW, like Cyclone says, the handler for .each should just be a model without the index. :)

这篇关于collection.each()不迭代模型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆