This is a good approach to filtering the core network for several attributes:
filterData: function(params) { // store original data for clearing filters this.originalModels = this.models.slice(); for (var key in params) { var val = params[key]; // if we are dealing with multiple values in an array // ie ['ford','bmw','mazda'] if (typeof val === "object") { var union = []; for (var k in val) { var subval = val[k]; var matched = _.filter(this.models, function(house) { return house.get(key) == subval; }); union = union.concat(matched); } this.models = union; } else { var results = _.filter(this.models, function(house) { return house.get(key) == val; }); this.models = results; } } // end for return this.reset(this.models); }, clearFilters: function() { return this.reset(this.originalModels); }
I tested it and it allows you to filter the collection as follows:
filterParams = {brand:['ford','bmw','mazda'], color:black} carCollection.filterData(filterParams);
It seems to work, but I don't know if there is a better way to do this.
I tested the Backbone.Collection.where() method, but it does not work if I want to say brand: ['bmw','mazda','ford']
source share