Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Filter Collection by Substring in Backbone.js

If I were to want to do an autocomplete for a collection, what would be the best way? I'd like to see if a search string is in any (or a select few) attributes in my model.

I was thinking something like...

this.collection.filter(function(model) {
    return model.values().contains($('input.search]').val());
})

Edit I'm sorry, I must not have explained it well enough. If I have a collection with attributes...

[ 
  { first: 'John', last: 'Doe'}, 
  { first: 'Mary', last: 'Jane'} 
]

I want to type in a into my search, catch the keyup event, and filter out { first: 'Mary', last: 'Jane'}, as neither John nor Doe contains an a.

like image 550
savinger Avatar asked Aug 16 '26 06:08

savinger


2 Answers

You can look at the model's attributes to do something like this...

var search = $('input.search]').val();
this.collection.filter(function(model) {
    return _.any(model.attributes, function(val, attr) {
        // do your comparison of the value here, whatever you need
        return ~val.indexOf(search);
    });;
});
like image 137
jcreamer898 Avatar answered Aug 17 '26 19:08

jcreamer898


You do not need to filter and compare values. Backbone has an inbuilt method where which fetches a subset of models from the collection.

http://backbonejs.org/#Collection-where

var friends = new Backbone.Collection([
  {name: "Athos",      job: "Musketeer"},
  {name: "Porthos",    job: "Musketeer"},
  {name: "Aramis",     job: "Musketeer"},
  {name: "d'Artagnan", job: "Guard"},
]);

var musketeers = friends.where({job: "Musketeer"});
like image 26
DhruvPathak Avatar answered Aug 17 '26 19:08

DhruvPathak



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!