Created
January 10, 2012 16:47
-
-
Save olivernn/1589967 to your computer and use it in GitHub Desktop.
The Plugin
This file contains 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
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 | |
}; |
This file contains 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
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