gpt4 book ai didi

javascript - SELECT binding : clearing the options observable array sets value observable property to undefined. 如何避免呢?

转载 作者:行者123 更新时间:2023-11-27 23:57:51 25 4
gpt4 key购买 nike

我有一个像这样的 knockout View 模型(大大简化的示例):

var vm = function() {
this.items = ko.observableArray();
this.selectedItemValue = ko.observable(null)

this.items.push({ value: "item1", text: "First item"});
this.items.push({ value: "item2", text: "Second item"});
};

我有一个绑定(bind)到这些属性的选择框,如下所示:

<select data-bind="value: selectedItemValue, options: items, optionsValue: 'value', optionsText: 'text'"></select>

当我从选择框中选择一个值,然后清除项目数组后,我的 selectedItemValue 属性变为未定义。 然后,当我重新填充我的数组时,它有一个项目具有我之前选择的值,我的 selectedItemValue 将被更正。

我认为这是因为它的源对象被删除了,我猜字符串值是通过引用传递给绑定(bind)的 selectedItemValue observable。

如何避免这种情况?我希望 保持选定的字符串值 在我清除并重新填充我的项目数组期间,选定的值可观察到不会改变。这是因为我不时通过 ajax 完全刷新数组,这种行为引入了一些难以修复的错误。

更新:

这个行为似乎与 select 绑定(bind)机制有关,它不会恢复到我最初选择的值,而是可选项中的第一项,在这种情况下更有意义。

A jsfiddle is here来证明我的问题。

最佳答案

你应该使用computed observable,只有当新值不是undefined时才会改变selectedItemValue:

View 模型:

    self.selectedItemValue = ko.observable(null);
self.selectedItemValueComp = ko.computed({
read: function() {
return self.selectedItemValue;
},
write: function(newValue) {
if (newValue) {
self.selectedItemValue(newValue);
}
}
});

HTML:

<select data-bind="value: selectedItemValueComp, options: items, optionsValue: 'value', optionsText: 'text'"></select>
<button type="button" data-bind="click: clearItems">Clear select items</button>
<button type="button" data-bind="click: refillItems">Refill select items</button>

<br/>
selectedItemValueComp: <strong data-bind="text: selectedItemValueComp()"></strong>
<br/>
selectedItemValue: <strong data-bind="text: selectedItemValue"></strong>

Demo

关于javascript - SELECT binding : clearing the options observable array sets value observable property to undefined. 如何避免呢?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22929980/

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