gpt4 book ai didi

javascript - knockout/选择 2 : Triggering select2 to update based on an observable option updating

转载 作者:行者123 更新时间:2023-11-29 18:15:21 25 4
gpt4 key购买 nike

从 Knockout.js 2.x 升级到 3.x 时,我注意到这不起作用:我有一个屏幕,其中有一个 <select>。取决于可观察的可观察数组,我包装了 <select>带有 Select2 包装器。

现在,过去是当其中一个选项 observables 更新时,选择也会更新。现在仍然如此。但是我无法让 Select2 绑定(bind)同时正确更新。

我正在使用 Select2 Github page 推荐的绑定(bind)处理程序:

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 以匹配(但它会更新支持选择)。

http://jsfiddle.net/mrmills/MfttX/1/

最佳答案

当您添加 optionsValue: 'choice' 时似乎工作正常:

<select data-bind="options: choices, 
optionsText: 'choice',
optionsValue: 'choice',
select2: {}"></select>

参见 fiddle

关于javascript - knockout/选择 2 : Triggering select2 to update based on an observable option updating,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23767356/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com