Skip to content

Instantly share code, notes, and snippets.

@Deraen
Last active August 29, 2015 13:57
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Deraen/9742112 to your computer and use it in GitHub Desktop.
Save Deraen/9742112 to your computer and use it in GitHub Desktop.
Knockout + Selectize.js
// Use
// ko.bindingHandlers.fooSearch = createAutocomplete({load: ...});
// viewModel.idHere = "123";
// viewModel.objHere = {_id: "123", name: "foo"};
// viewModel.objHere.subscribe(function(val) { ... selected obj! ... });
//
// <input type="text" data-bind="value: idHere, fooSearch: objHere"/>
function createAutocomplete(override) {
return {
init: function(el, valueAccessor, allBindingsAccessor) {
var item = valueAccessor();
var s = $(el).selectize(_.extend({
valueField: "_id",
onChange: function(v) {
var data = this.options[v];
item(data);
},
create: false,
maxItems: 1,
openOnFocus: false
}, override))[0].selectize;
var bindings = allBindingsAccessor();
if (ko.isObservable(bindings.value)) {
bindings.value.subscribe(function(newVal) {
s.setValue(newVal);
});
}
var data = ko.unwrap(item);
if (data) {
s.updateOption(data._id, data);
}
}
};
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment