Ben*_*ger 6 javascript collections filter backbone.js underscore.js
我有一个Backbone.Collection完整的模型; 让我们说模型是Car.这个系列是一个很棒的大清单Cars.我希望能够从列表中选择一些特定的汽车ID,然后才能从这个集合中获得所选的汽车对象.
我的代码块不起作用; 我确信有一种方法可以使用Backbone.js/Underscore.js ...我对Backbone/Underscore也很新鲜.
CarList = Backbone.Collection.extend({
model: Car,
filterWithIds: function(ids) {
return this.filter(function(aCar) { return _.contains(ids, car.id); }
}
});
Run Code Online (Sandbox Code Playgroud)
有什么指针吗?
Ben*_*ger 12
好的,我想我已经知道了.它接近我原来的代码块,但更新的filterWithIds功能在这里.
filterWithIds: function(ids) {
return _(this.models.filter(function(c) { return _.contains(ids, c.id); }));
}
Run Code Online (Sandbox Code Playgroud)
对于那些跟随CoffeeScript(我)的人来说,这是CoffeeScript版本.
filterWithIds: (ids) -> _(@models.filter (c) -> _.contains ids, c.id)
Run Code Online (Sandbox Code Playgroud)
这是我的答案; 任何代码味道?