I'm using what I believe to be the generally accepted ko.bindingHandler.select2:

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

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

However, this seems to have a couple of issues. In this question I'd like to find an answer for how to make the View update when a change to the Model is made.

I've created a jsFiddle which demonstrates the issue. I have a simple setTimeout() function that sets the Model's selectedValue after 0.25 seconds to emulate behaviour similar to the Model loading data via an Ajax call. In the example the dropdown value is not updated when Select2 is used but appears to work just fine for a normal dropdown.

Full Solution : My updated custom binding now looks like this...

ko.bindingHandlers.select2 = {
init: function (element) {
    $(element).select2({});

    ko.utils.domNodeDisposal.addDisposeCallback(element, function () {
        $(element).select2('destroy');
    });
},
update: function (element, valueAccessor) {
    var value = valueAccessor();
    var valueUnwrapped = ko.utils.unwrapObservable(value);
    $(element).val(valueUnwrapped).trigger('change');
}

};

In my HTML I'm now passing in the value to the custom binding.

data-bind="select2: selectedValueS2
有帮助吗?

解决方案

OK, seems that I was able to figure out where the issue was. If you update dropdown value when value changes and then call trigger, it will work:

$(element).val(value()).trigger('change');

http://jsfiddle.net/tkirda/Mmuvx/5/

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top