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

@jeffrey_doucet @Brian_Bancroft Canadians, self define themselves as NOT American, rather than being Proud Canadians
Retweeted by @dyardy Why do so many Canadians obsess over American policy that won’t impact us while being fairly ambivalent to day-to-d……
@melrobbins I was looking for 50$ earlier today, and still can't find it...ideas :)
Trump Watches Up To 8 Hours Of TV Per Day | HuffPost #SmartNews ===that explains everything…
Retweeted by @dyardy Boston