[英]Backbone.js: How do I filter a collection of objects by an array of model IDs?
I've got a Backbone.Collection
full of models; 我有一个充满模型的Backbone.Collection
; let's say that model is Car
. 让我们说模型是Car
。 This collection is a great, big list of Cars
. 这个系列是一个伟大的Cars
名单。 I want to be able to have a few specific car IDs selected from a list, and then be able to get just those selected car objects out of this collection. 我希望能够从列表中选择一些特定的汽车ID,然后才能从这个集合中获得所选的汽车对象。
My code block below isn't working; 我的代码块不起作用; I'm sure there's a way to do this with Backbone.js/Underscore.js… I'm pretty fresh to Backbone/Underscore, too. 我确信有一种方法可以使用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); }
}
});
Any pointers? 有什么指针吗?
Okay, I think I've got it. 好的,我想我已经知道了。 It's close to my original code block, but the updated filterWithIds
function is here. 它接近我的原始代码块,但更新的filterWithIds
函数在这里。
filterWithIds: function(ids) {
return _(this.models.filter(function(c) { return _.contains(ids, c.id); }));
}
For those following along in CoffeeScript (I am), here's the CoffeeScript version. 对于那些跟随CoffeeScript(我)的人来说,这是CoffeeScript版本。
filterWithIds: (ids) -> _(@models.filter (c) -> _.contains ids, c.id)
It's my answer; 这是我的答案; any code smell? 任何代码味道?
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.