Created
August 21, 2012 05:36
-
-
Save GuillaumeBiton/3412192 to your computer and use it in GitHub Desktop.
Allow searches on Backbone collection
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Usage: | |
collection.searchBy({attribute: "searched value", attribute: "searched value", ...}); | |
collection.search("query"); |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
_.extend(Backbone.Collection.prototype, { | |
searchBy: function(attrs){ | |
if(_.isEmpty(attrs)) return null; | |
return this.filter(function(model){ | |
for(var key in attrs){ | |
if(~model.get(key).toLowerCase().indexOf(attrs[key].toLowerCase())) return true; | |
} | |
return false; | |
}); | |
}, | |
search: function(obj){ | |
if(_.isEmpty(obj)) return null; | |
return this.filter(function(model){ | |
for(var key in model.attributes){ | |
if(~model.get(key).toLowerCase().indexOf(obj.toLowerCase())) return true; | |
} | |
return false; | |
}); | |
} | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment