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

  

        $("#txtEvaluator").select2({
            placeholder: 'Evaluator',
            multiple:true,
            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) {
            $('#txtEvaluatorId').val(e.val).change();
        }).on("select2-removed", function (e) {
            $('#txtEvaluatorId').val('').change();
        });

Option 2) Using binding handler

  

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

        ko.utils.domNodeDisposal.addDisposeCallback(element, function () {
            $(element).select2('destroy');
        });
    },
    update: function (element) {
        $(element).trigger('change');
    }
};

Author

Admin

comments powered by Disqus