Select2 and Knockout Binding

If using Select2 and Knockout, you have the following options for hooking up to html elements. In both of these cases my viewmodel has a property called EvaluatorList with collection object properties of DisplayName and Code.


1.) Manual

JavaScript looking like


            placeholder: 'Evaluator',
            allowClear: true,
            id: function (e) { return e.Code },
            data: { results: ko.toJS(viewModel.EvaluatorList()), text: 'DisplayName' },
            formatSelection: function (item) { return item.DisplayName; },
            formatResult: function (item) { return item.DisplayName; }
        }).on("select2-selecting", function (e) {
        }).on("select2-removed", function (e) {

Option 2) Using binding handler


ko.bindingHandlers.select2 = {
    init: function (element, valueAccessor, allBindingsAccessor) {
        var obj = valueAccessor(),
            allBindings = allBindingsAccessor(),
            lookupKey = allBindings.lookupKey;
        if (lookupKey) {
            var value = ko.utils.unwrapObservable(allBindings.value);
            $(element).select2('data', ko.utils.arrayFirst(, function (item) {
                return item[lookupKey] === value;

        ko.utils.domNodeDisposal.addDisposeCallback(element, function () {
    update: function (element) {



comments powered by Disqus


Recent Tweets

@ACLU n to pay for a long time. I yu the
#Xamarin Certified Trophy arrived today! @XamarinU thanks!
Retweeted by @dyardy #PowerShell and Kerberos double hop. Slides, module, and demos. #PshSummit
@danrigby @Raspberry_Pi Very cool, let us know how it goes, thx