淘汰/选择2:基于可观察到的选项更新触发select2更新 [英] Knockout/Select2: Triggering select2 to update based on an observable option updating
问题描述
从Knockout.js 2.x升级到3.x时,我注意到这不起作用:我有一个屏幕,其中有一个<select>
,具体取决于可观察到的可观察对象数组,并且包装了
When upgrading from Knockout.js 2.x to 3.x, I've noticed this not working: I have a screen where I have a <select>
depending on an observable array of observables, and I wrap the <select>
with a Select2 wrapper.
现在,它使用的是当观测选项之一被更新时,选择将更新.情况仍然如此.但是我无法同时选择Select2绑定来正确更新.
Now, it used to be that when one of the option observables was updated, the select would update. And that is still the case. But I can't get the Select2 binding to update properly at the same time.
我正在使用 Select2 Github页面:
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;
}
})();
下面是一个示例.您会注意到,当更改代表select中的项的输入之一的值时,它不会更新Select2以使其匹配(但是会更新后备select).
Below is an example. You'll notice that when you change the value of one of the inputs that represent the items in the select, it doesn't update the Select2 to match (but it does update the backing select).
http://jsfiddle.net/mrmills/MfttX/1/
推荐答案
当您添加optionsValue: 'choice'
时,它似乎工作正常:
It seems to work fine when you add the optionsValue: 'choice'
:
<select data-bind="options: choices,
optionsText: 'choice',
optionsValue: 'choice',
select2: {}"></select>
请参见 小提琴
See fiddle
这篇关于淘汰/选择2:基于可观察到的选项更新触发select2更新的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!