Search code examples
javascriptbackbone.jsunderscore.js

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.


Solution

  • 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);
        });;
    });