Created
December 18, 2013 07:19
-
-
Save jeffling/8018535 to your computer and use it in GitHub Desktop.
Fuzzy searching with fuse.js on Backbone Collections
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
class FuzzySearchCollection extends Backbone.Collection | |
# | |
# Fuzzy searching with fuse.js | |
# | |
# 1. populate searchableFields with the model attributes you want to search on | |
# 2. collection.buildSearchIndex(), with optional options -> http://kiro.me/projects/fuse.html#options | |
# 3. collection.search 'query' | |
# | |
searchableFields: [] | |
buildSearchIndex: (options = {}) -> | |
defaultOptions = | |
keys: @searchableFields | |
id: 'id' | |
@_fuse = new Fuse _.pluck(@models, 'attributes'), _.defaults(options, defaultOptions) | |
# returns copy of collection with search results | |
search: (query) -> | |
searchResults = _(@_fuse.search query) | |
@filter (task) => | |
searchResults.contains(task.get 'id') |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment