Vik*_*ram 1 javascript backbone.js backbone.js-collections
我的Collection收集了一些记录,我只需要显示前10条记录.我试过了
this.collection.each(function(){
if (count == 10) break;
//pass model to view
});
Run Code Online (Sandbox Code Playgroud)
不幸的是,break不能用于underscore.js的each()API.请参考这里:如何在underscore.js中打破_.each函数
如何编写一个过滤器,只从集合中选择前十名
this.collection.filter();
Run Code Online (Sandbox Code Playgroud)
更新:collection.first(10)提取了我的过滤列表.但是,我仍然需要将.each()链接到此集合来处理集合项.collection.first()不允许链.请参阅我选择的答案以获得解决方案.
例如
this.collection.first(10)
Run Code Online (Sandbox Code Playgroud)
然后,如果您需要使用每个模型,例如:
var collection = new Backbone.Collection([{id:1}, {id:2}, {id:3}, {id:4}, {id:5}],{model: Backbone.Model});
var newCollection = new Backbone.Collection(collection.first(2));
newCollection.each(function(model){
alert(JSON.stringify(model.toJSON()));
});
Run Code Online (Sandbox Code Playgroud)
看到jsfiddle.请注意,还有另一种方法可以使用本主题中所述的Underscore链方法.
看看Backbone doc和Underscore doc.