开发者

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; let's say that model is Car. This collection is a great, big list of Cars. I want to be abl开发者_JAVA百科e 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.

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.

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: 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.

filterWithIds: (ids) -> _(@models.filter (c) -> _.contains ids, c.id)

It's my answer; any code smell?

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜