Forum Moderators: open

Message Too Old, No Replies

[Backbone.js] where or filter

         

skoff18

7:48 pm on May 3, 2015 (gmt 0)

10+ Year Member



Hi guys,

I've been using backbone.js for a while now and I need to filter a collection of models. I can do it pretty easily. The only thing i'm stuck on is how to filter on a single attribute but with different values dynamically. I can do it like that :

Collection = Cars
Model = Car
Attributes = make, model, year, type


Cars.filter(function(car) {
return car.get('make') == 'Honda' || car.get('make') == 'Toyota';
});


My problem is that these selection are made dynamically by the user so I never know how many choices will be made I can't assume anything..

I hope I'm clear enough so you can help me solve my problem!

Thanks

Fotiman

1:48 pm on May 4, 2015 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member Top Contributors Of The Month



I haven't used Backbone much. If I understand you correctly, the values like 'Honda' and 'Toyota' in your example would be values that the user chose from a list, and you're wondering how to make the filter dynamic to work with the values the user has selected, correct?

I'd probably start by trying to create an array of attribute/value pairs:

var filterAttributes = [];
// As user selects values, add or remove them to this array:
filterAttributes.push({
attr: 'make',
val: 'Honda'
});

Then in the filter function, iterate over that array:

Cars.filter(function(car) {
for (var i = 0; i < filterAttributes.length; i++) {
if (car.get(filterAttributes[i].attr) === filterAttributes[i].val) {
return true;
}
}
// If you get here, none of the attributes matched
return false;
});

Next, I might look at making the filterAttributes array a property of the Cars collection, perhaps using the Collection extend [backbonejs.org] method.

Hope this helps get you started.