0
votes

I'm using the Knockout.js binding provided by Select2, which is as follows:

ko.bindingHandlers.select2 = {
    init: function (element, valueAccessor, allBindingsAccessor) {
        var obj = valueAccessor(),
            allBindings = allBindingsAccessor()
        $(element).select2(obj);

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

I have a binding on a hidden element as well:

<input type="hidden" class="bigdrop" id="seriesInput" data-bind="value: seriesID, select2: {minimumInputLength: 4, query: $root.nameQuery, formatResult: $root.ownerFormatResult, formatSelection: $root.ownerFormatSelection }" style="margin-left: 1px; width:340px" />

The issue I'm having is that when the select2 binding is created, it changes the pre-existing value in the observable seriesID to the string "[object Object]". I'm fairly certain it's an issue with the binding handler, but I cannot find a working one anywhere. Has anyone found a fix for this?

2

2 Answers

0
votes

I'd need to see more of your code to know why you're having that issue, but here's an example with your code that works fine: http://jsfiddle.net/Y93Wm/

I used this viewmodel code:

ko.applyBindings({
    seriesID: ko.observable('series-id'),
    nameQuery: function(o) {
        o.callback({
            more: false,
            results: [
                { id: "CA", text: "California" },
                { id: "AL", text: "Alabama" },
                {id: 'AA1', text: 'aaaaabc'},
                {id: 'AA2', text: 'aaaaabcd'},
                {id: 'AA', text: 'aaaaaa'},
                {id:'BB', text: 'bbbbbbb'}]
        });
    },
    ownerFormatResult: function(o) { return o.text },
    ownerFormatSelection: function(o) { return o.text }
});
-1
votes

Make sure to tell select to how to update your observable. So you need to add a change handler to the init function for when select2 changes value.