Skip to content

Instantly share code, notes, and snippets.

@GuillaumeBiton
Created August 21, 2012 05:36
Show Gist options
  • Save GuillaumeBiton/3412192 to your computer and use it in GitHub Desktop.
Save GuillaumeBiton/3412192 to your computer and use it in GitHub Desktop.
Allow searches on Backbone collection
Usage:
collection.searchBy({attribute: "searched value", attribute: "searched value", ...});
collection.search("query");
_.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