6

我确信这是一个非常容易解决的问题,但到目前为止我发现的所有帖子似乎都没有直接解决这个问题:我如何遍历一个集合来获取每个模型?

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

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]);
 }

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

4

5 回答 5

24

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

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

第二种方法是用each方法:

myCollection.each(function(model, index, [context]) {...});
于 2013-04-15T12:18:36.813 回答
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

于 2013-04-15T12:25:15.973 回答
0

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

于 2013-04-15T12:18:23.937 回答
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);
    }

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

于 2013-04-15T12:19:23.557 回答
0

我使用了下划线图。

docs = Backbone.Collection.extend();

this.subViews = _.map(docs.models, function(doc) {
    return new DocView({ model: doc });
}, this);
于 2014-07-22T16:27:42.460 回答