-
-
Save tzmartin/89e9eeeadb67808c35d8 to your computer and use it in GitHub Desktop.
This file contains hidden or 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
// 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