Udders
Udders

Reputation: 6976

backbone filter collection to return models by name?

I am trying to filter a collection a collection by a models attribute (name),

byName: function(searchParam) {
    var filtered = this.filter(function(model){
        console.log(model.get('name').toLowerCase());
        console.log(searchParam.toLowerCase());
        if(model.get('name').toLowerCase().indexOf(searchParam.toLowerCase()) !== -1) {
            model.trigger('show');
        } else {
            model.trigger('hide');
        }
    });
}

I am having a small problem though, my search parameter at the moment is just simply "a". It should therefore be returning all models that have a name with "a" in it.

However I have 2 models that should be returned the names of these are "abba" and "AAAS". I was assuming that "AAAS" was not being return as my search terms was lowercase, and the model name was uppercase, so I added a .toLowerCase() but it still only returns "abba" why?

Upvotes: 2

Views: 253

Answers (1)

Radosław Miernik
Radosław Miernik

Reputation: 4094

According to documentation of _.filter (Backbone's Collection.filter uses it), your filtered array should be empty - it should contain only elements, which predicate returned truthy value - your function returns undefined which is falsy value. Try this:

...
if(model.get('name').toLowerCase().indexOf(searchParam.toLowerCase()) !== -1) {
    model.trigger('show');
    return true;
} else {
    model.trigger('hide');
}
...

Now filtered should contain all models with searchParam in it's name (case insensitive).

Upvotes: 1

Related Questions