Skip to content

Instantly share code, notes, and snippets.

@jeffling
Created December 18, 2013 07:19
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 jeffling/8018535 to your computer and use it in GitHub Desktop.
Save jeffling/8018535 to your computer and use it in GitHub Desktop.
Fuzzy searching with fuse.js on Backbone Collections
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