Skip to content

Instantly share code, notes, and snippets.

@evenkiel
Created November 11, 2013 19:14
Show Gist options
  • Save evenkiel/7418675 to your computer and use it in GitHub Desktop.
Save evenkiel/7418675 to your computer and use it in GitHub Desktop.
Custom knockout binding handler to work with the Select2 project
//
// Assumes that you are binding to a hidden input element.
//
// Bindings:
// * select2 : passthrough options to the select2 javascript call
// * selectedItem : object to initially select, or null
// * itemMapper : defaaults to {id: 'id', text: 'text'}
// * items : set of items to init the selection list with
//
// example:
// <input type="hidden" data-bind="select2: {placeholder: 'Select me', allowClear : true},
// selectedItem: selectme, items: clients mapper: {id: 'Id', text:'ClientName'} />
//
ko.bindingHandlers.select2 = {
init: function (element, valueAccessor, allBindingsAccessor) {
var obj = valueAccessor();
var allBindings = allBindingsAccessor();
var itemMapper = allBindings.itemMapper || {id : 'id', text: 'text'};
obj.data = obj.data || {results: [], text: (itemMapper.text || 'text')};
var items = ko.utils.unwrapObservable(allBindings.items);
_(items).each(function (anitem) {
var theid = anitem[itemMapper.id];
var thetext = anitem[itemMapper.text];
obj.data.results.push({ id: theid, text: thetext });
});
$(element).select2(obj);
var selected = ko.utils.unwrapObservable(allBindings.selectedItem);
if (null != selected) {
$(element).select2("val", selected[itemMapper.id]);
}
ko.utils.domNodeDisposal.addDisposeCallback(element, function () {
$(element).select2('destroy');
});
// keeps the backing ko model object in sync with select2 selection events
$(element).on('change', function updateSelect2ObservableModel(val, added, removed) {
var idkey = itemMapper.id;
var newkey = $(val.target).select2('val');
var items = ko.utils.unwrapObservable(allBindings.items);
var match = _(items).find(function(iter) {
return iter[idkey] == newkey;
});
allBindings.selectedItem(match);
});
},
update: function (element, valueAccessor, allBindingsAccessor) {
var obj = valueAccessor(),
allBindings = allBindingsAccessor(),
itemMapper = allBindings.itemMapper || { id: 'id', text: 'text' };
var disable = allBindings.disable ? ko.utils.unwrapObservable(allBindings.disable) : false,
enable = allBindings.enable ? ko.utils.unwrapObservable(allBindings.enable) : true;
if (enable && !disable) {
$(element).select2("enable");
} else {
$(element).select2("disable");
}
var selected = ko.utils.unwrapObservable(allBindings.selectedItem);
if (! _(selected).isUndefined())
$(element).select2("val", selected[itemMapper.id]);
$(element).trigger('change');
}
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment