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

Maybe resolved itself, after resetting emulator and couple restarts - will let you know
@MillerMark A few weeks ago you tweeted that something huge/incredible was coming....what is/was it? (I am hoping s……
Oddly, it won't hit breakpoints in XF .net standard 2 project now either
@JamesMontemagno Updated to 15.7 preview 2 Visual Studio - now having lots of odd thread issues when starting debug……