Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 313
Ben Kreeger Avatar asked Jun 22 '11 15:06

Ben Kreeger


1 Answers

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?

like image 76
Ben Kreeger Avatar answered Sep 28 '22 19:09

Ben Kreeger