Skip to content

Instantly share code, notes, and snippets.

@g0t4
Created April 15, 2013 03:47
Show Gist options
  • Save g0t4/5385572 to your computer and use it in GitHub Desktop.
Save g0t4/5385572 to your computer and use it in GitHub Desktop.
knockoutjs binder for bootstrap typeahead
// FYI YMMV this was just a first pass and I know it has some issues at times that I need to workout
// usage
// source: a function that takes the query (text entered by user) and a callback (process), if source is synchronous it should return the results and ignore the callback, otherwise it should return nothing and use the callback to return the results
// selectedId: the model property to bind the id to
// value: the model property to bind the text value of the selection to
// data-bind="typeahead: { source: App.view.targets.typeAheadSource, selectedId: target._id }, value: target.name"
// note I also use this little helper class to wrap up all this functionality
// it takes a url to query the results for asynchrnous data sets and has an init method to call to query the data initially.
function TypeAhead(url) {
var self = this;
self.data = ko.observableArray([]);
self.typeAheadSource = function () {
return self.data();
};
self.init = function () {
$.ajax({
url: url,
dataType: 'json'
}).success(self.data);
};
return self;
}
require(['knockout', 'jquery.elastic'], function (ko) {
ko.bindingHandlers.typeahead = {
init: function (element, valueAccessor, allBindingsAccessor, viewModel, bindingContext) {
var parameters = ko.toJS(valueAccessor());
var defaults = {
items: 10,
minLength: 0
};
var source = parameters.source;
var queryResults = {};
parameters.source = function (query, process) {
var processText = function (results) {
results.forEach(function (r) { queryResults[r.text] = r._id});
process(results.map(function (r) { return r.text; }));
}
var synchronousResults = source(query, processText);
if (!synchronousResults) {
return;
}
return processText(synchronousResults);
}
allBindingsAccessor().value.subscribe(function (selectedText) {
valueAccessor().selectedId(queryResults[selectedText])
})
$(element).typeahead($.extend(defaults, parameters));
}
};
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment