从Backbone Collection获取每个模型

时间:2013-04-15 12:12:13

标签: javascript backbone.js underscore.js

我确信这是一个非常简单的解决方案,但到目前为止我发现的帖子似乎都没有直接解决这个问题:如何循环收集以获取每个模型?

我尝试使用的第一种方法是下划线的每种方法。这是我的电话和功能:

collection_var.each(paintThings);

这是我的功能:

function paintThings() {
        console.log(this);
        console.log(this.model);
            var thing_type = this.model.get("type"),
                thing_other = this.model.get("otherAttribute");

                console.log(this.model);
                console.log(thing_type);
                console.log(thing_other);
        }

现在,这是未定义的,并且this.model错误:

Uncaught TypeError: Cannot read property 'model' of undefined 

我知道答案很简单,但这让我发疯了!我是新来的强调。这里有人可以帮忙吗?如果它们更快/更好,我也会接受其他非下划线方法。

我也试过这个:

 for (var i = 0, l = collection_var.length; i < l; i++) {
            console.log(collection_var[i]);
 }

但这并没有给我我想要的东西。

5 个答案:

答案 0 :(得分:24)

第一种方法:使用集合的models属性:

var myModel
for(var i=0; i<myCollection.length; i++) {
  myModel = myCollection.models[i];
}

第二种方法是使用each方法:

myCollection.each(function(model, index, [context]) {...});

答案 1 :(得分:3)

迭代集合的每个模型,例如。由backbone.js提供

books.each(function(book) {
  book.publish();
});

在你的情况下它应该是这样的

collection_var.each(function(paintThing){
    console.log(paintThing);
    var thing_type = this.model.get("type"),
        thing_other = this.model.get("otherAttribute");

    console.log(paintThing);
    console.log(thing_type);
    console.log(thing_other);
});

http://backbonejs.org/#Collection-Underscore-Methods

答案 2 :(得分:0)

我认为你应该尝试collection_var.models.each(paintThings)。这应该可以让您直接访问集合的模型。

答案 3 :(得分:0)

好的,愚蠢的错误!我只需要将额外的参数传递给函数,这样我就可以触摸模型了。

像这样:

function paintThings(thing) {
    //returns model
    console.log(thing);
        var thing_type = thing.get("type"),
            thing_other = thing.get("otherAttribute");

            //These all respond directly
            console.log(thing);
            console.log(thing_type);
            console.log(thing_other);
    }

我仍然会审查所有答案并接受最优雅的解决方案!

答案 4 :(得分:0)

我使用了下划线地图。

docs = Backbone.Collection.extend();

this.subViews = _.map(docs.models, function(doc) {
    return new DocView({ model: doc });
}, this);