str*_*ght 6 javascript backbone.js underscore.js
我确信这是一个非常简单的解决方案,但到目前为止我发现的帖子似乎都没有直接解决这个问题:我如何循环收集以获得每个模型?
我试图使用的第一种方法是下划线的每种方法.这是我的电话和功能:
collection_var.each(paintThings);
Run Code Online (Sandbox Code Playgroud)
这是我的功能:
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);
}
Run Code Online (Sandbox Code Playgroud)
现在,这是未定义的,并且this.model错误:
Uncaught TypeError: Cannot read property 'model' of undefined
Run Code Online (Sandbox Code Playgroud)
我知道答案很简单,但这让我发疯了!我是新来的强调.这里有人可以帮忙吗?如果它们更快/更好,我也会接受其他非下划线方法.
我也试过这个:
for (var i = 0, l = collection_var.length; i < l; i++) {
console.log(collection_var[i]);
}
Run Code Online (Sandbox Code Playgroud)
但那不是给我我想要的东西.
Loa*_*oof 24
第一种方法:使用models集合的属性:
var myModel
for(var i=0; i<myCollection.length; i++) {
myModel = myCollection.models[i];
}
Run Code Online (Sandbox Code Playgroud)
第二种方法是用这个each方法:
myCollection.each(function(model, index, [context]) {...});
Run Code Online (Sandbox Code Playgroud)