Created
September 22, 2013 09:58
-
-
Save Devristo/6658539 to your computer and use it in GitHub Desktop.
Select2 Knockout.js Binding Handler supporting 'selected' and the 'on' event bindings
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
ko.bindingHandlers.select2 = { | |
init: function (element, valueAccessor, allBindingsAccessor) { | |
var obj = valueAccessor(), | |
allBindings = allBindingsAccessor(), | |
lookupKey = allBindings.lookupKey; | |
var select2 = $(element).select2(obj); | |
// Bind events | |
if ("on" in obj) { | |
for (var event in obj.on) { | |
select2.on(event, obj.on[event]); | |
} | |
} | |
if (lookupKey) { | |
var value = ko.utils.unwrapObservable(allBindings.value); | |
$(element).select2('data', ko.utils.arrayFirst(obj.data.results, function (item) { | |
return item[lookupKey] === value; | |
})); | |
} | |
// The selected binding is similar to the value binding, but it is in array format and preserves the objects | |
var selected = obj.selected; | |
if (selected) { | |
$(element).select2('data', ko.utils.unwrapObservable(selected)); | |
select2.on('change', function (e) { | |
if (ko.isObservable(selected)) | |
selected($(element).select2('data')); | |
}); | |
} | |
ko.utils.domNodeDisposal.addDisposeCallback(element, function () { | |
$(element).select2('destroy'); | |
}); | |
}, | |
update: function (element, valueAccessor, allBindingsAccessor) { | |
var allBindings = allBindingsAccessor(); | |
// If we have a selected binding, update the select2 to reflect any changes (creates a dependency on the observable) | |
var selected = ko.utils.unwrapObservable(valueAccessor().selected); | |
if (selected) { | |
$(element).select2('data', selected); | |
} | |
$(element).trigger('change'); | |
} | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Hi @Devristo, could you please post a snippet of your html that goes with this binding? I am having trouble binding to the "select2-opening" event with knockout.
Thanks a bunch.
Jonathan