Skip to content

Instantly share code, notes, and snippets.

@tzmartin
Forked from procky/gist:2fa788d564ce0850aa76
Last active August 29, 2015 14:16
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save tzmartin/89e9eeeadb67808c35d8 to your computer and use it in GitHub Desktop.
Save tzmartin/89e9eeeadb67808c35d8 to your computer and use it in GitHub Desktop.
// backbone collections lack a search functionality. This adds it to all collections.
// fuse.js is the library that powers the fuzzy search and requires being downloaded and included into your app
// http://kiro.me/projects/fuse.html
_.extend(Backbone.Collection.prototype, {
searchableFields: null,
buildSearchIndex: function(options) {
options = (typeof options !== 'undefined') ? options : {};
var defaultOptions = {
keys: this.searchableFields,
id: 'id'
};
return this.fuse = new Fuse(_.pluck(this.models, 'attributes'), _.defaults(options, defaultOptions));
},
// returns copy of collection with search results
search: function(query) {
var searchResults = this.fuse.search(query);
// returned in the order of the collection
// return this.filter(function(model) {
// return _.contains(searchResults, model.get('id'));
// },this);
//returned in the order of the search result
return _.filter(searchResults, function(modelID) {
return _.contains(this.pluck("id"), modelID);
},this);
}
});
// Example usage:
// collection1 is a collection and is populated. attName is an attribute on the models inside the collection.
// the console.log will return the models that match the search term.
collection1.searchableFields = ['attName'];
collection1.buildSearchIndex();
var result = collection1.search('test');
console.log(result);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment