当从Knockout.js 2.x升级到3.x时,我注意到这不起作用:我有一个屏幕,我有一个<select>
取决于一个可观察的可观察数组,我用Select2包装器包装<select>
。
现在,它曾经是当更新了一个选项observable时,select会更新。情况仍然如此。但我无法同时正确更新Select2绑定。
我正在使用Select2 Github page推荐的绑定处理程序:
ko.bindingHandlers["select2"] = {
after: ["options", "value", "selectedOptions"],
init: function (element, valueAccessor) {
$(element).select2(ko.unwrap(valueAccessor()));
ko.utils.domNodeDisposal.addDisposeCallback(element, function() {
$(element).select2("destroy");
});
},
update: function (element, valueAccessor, allBindingsAccessor) {
//trying various methods to register interest with dependency checking
//var allBindings = allBindingsAccessor();
//if (allBindings.options) { allBindings.options(); }
//if (allBindings.value) { allBindings.value(); }
//if (allBindings.selectedOptions) { allBindings.selectedOptions(); }
$(element).trigger("change");
}
};
(function () {
var updateOptions = ko.bindingHandlers["options"]["update"];
ko.bindingHandlers["options"]["update"] = function (element) {
var ret = updateOptions.apply(null, arguments);
var $el = $(element);
if ($el.data("select2")) { $el.trigger("change"); }
return ret;
}
})();
(function () {
var updateSelectedOptions = ko.bindingHandlers["selectedOptions"]["update"];
ko.bindingHandlers["selectedOptions"]["update"] = function (element) {
var ret = updateSelectedOptions.apply(null, arguments);
var $el = $(element);
if ($el.data("select2")) { $el.trigger("change"); }
return ret;
}
})();
以下是一个例子。您会注意到,当您更改表示选项中项目的其中一个输入的值时,它不会更新Select2以匹配(但它会更新后备选择)。
答案 0 :(得分:4)
添加optionsValue: 'choice'
:
<select data-bind="options: choices,
optionsText: 'choice',
optionsValue: 'choice',
select2: {}"></select>
参见 fiddle