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

"Setting up and Getting Started with Power BI Embedded | Data Exposed"… #webcast #feedly
Retweeted by @dyardy @scottgu @victoriabeckham Worlds collide, double take on that photo!
@scottgu @victoriabeckham Worlds collide, double take on that photo!
@projectedxyz It is really easy, what are you doing (isn't this data which on the web)