gpt4 book ai didi

javascript - knockout : How can I set the value of a select box whose options are javascript objects?

转载 作者:行者123 更新时间:2023-11-30 10:35:07 24 4
gpt4 key购买 nike

我有一个 select 元素,它使用 options 绑定(bind)绑定(bind)到一个复杂的 javascript 对象列表:

<select data-bind="options: availableCountries, optionsText: 'countryName', value: selectedCountry, optionsCaption: 'Choose...'"></select>

其中 availableCountries 是一个可观察的 javascript 对象数组。你可以看到完整的例子 in this fiddle .

现在,当我在列表中选择一个项目时,它工作正常。但是,如果我需要更新应用程序其他部分的值,只有使用与 availableCountries 数组中的完全相同的 Country 对象,我才能这样做。这个related question也成立了,但不幸的是,它并没有解决我的问题。

options binding 的文档中,他们预料到了这个问题,并说我应该使用 optionsValue 绑定(bind):

Typically you’d only want to use optionsValue as a way of ensuring that KO can correctly retain selection when you update the set of available options. For example, if you’re repeatedly getting a list of “car” objects via Ajax calls and want to ensure that the selected car is preserved, you might need to set optionsValue to "carId" or whatever unique identifier each “car” object has, otherwise KO won’t necessarily know which of the previous “car” objects corresponds to which of the new ones.

但不幸的是,这不会起作用,因为它还会影响值绑定(bind) - 如果我将 optionsValue 设置为 'countryName'selectedCountry 将只包含国家名称而不是整个对象。

我正在寻找一种方法来结合这些。我仍然希望值是整个对象,但我希望选项值比较使用我指定的特定属性。基本上,是这样的:

<select data-bind="options: availableCountries, optionsText: 'countryName', optionsComparator: 'countryName', value: selectedCountry, optionsCaption: 'Choose...'"></select>

但是,据我所知,这涉及修改 value 绑定(bind)。我还有其他选择吗?我可以用其他方式解决这个问题吗?扩展器?自定义绑定(bind)处理程序?

最佳答案

我做了一个选定的绑定(bind)来解决这个问题,检查我的绑定(bind)集合

Demo,下拉在页面末尾 http://jsfiddle.net/H8xWY/8/

https://github.com/AndersMalmgren/Knockout.Bindings

代码

ko.bindingHandlers.selected = {
init: function (element, valueAccessor, allBindingsAccessor) {
var selected = valueAccessor();
var items = ko.utils.unwrapObservable(allBindingsAccessor().options);
var key = allBindingsAccessor().optionsKey ? allBindingsAccessor().optionsKey : allBindingsAccessor().optionsText;

var observable = ko.computed({
read: function () {
var value = ko.utils.unwrapObservable(selected);
return ko.utils.arrayFirst(items, function (item) {
return value != null ? ko.utils.unwrapObservable(item[key]) == ko.utils.unwrapObservable(value[key]) : false;
});
},
write: function (value) {
writeValueToProperty(selected, allBindingsAccessor, "selected", value);
}
});

ko.applyBindingsToNode(element, { value: observable });
}
};

关于javascript - knockout : How can I set the value of a select box whose options are javascript objects?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14447565/

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