Skip to content

Instantly share code, notes, and snippets.

@olivernn
Created January 10, 2012 16:47
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 olivernn/1589967 to your computer and use it in GitHub Desktop.
Save olivernn/1589967 to your computer and use it in GitHub Desktop.
The Plugin
Model.Lunr = function (config) {
var index = Lunr('name', config)
var addInstanceToIndex = function (instance) {
setTimeout(function () {
index.add(instance.attr())
}, 0)
}
var plugin = function (klass) {
var buildIndex = function () {
klass.all().forEach(addInstanceToIndex)
}
var rebuildIndex = function () {
index.empty()
buildIndex()
}
klass.extend({
search: function (term) {
if (!term) return klass.chain([])
return klass.chain(index.search(term).map(function (id) {
return klass.find(id)
}))
},
initSearchIndex: function () {
buildIndex()
klass.bind('add', addInstanceToIndex)
klass.bind('changed', rebuildIndex) // note this event doesn't actually exist in js-model, but if it did...
klass.bind('remove', rebuildIndex)
},
})
}
return plugin
};
var Post = Model('post', function () {
this.use(Model.Lunr(function () {
this.field('body')
this.field('title', {
'multiplier': 10
})
}))
})
Post.search('awesome') // returns a sorted array.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment