我有一个使用options,optionsValue,optionsText和optionsCaption绑定绑定到可观察数组的下拉列表(选择控件)。
如果我选择了一个选项,然后将其删除,则下拉列表会选择第一个项目。我希望它将选定的值设置为undefined,而不必将空项添加到observable数组。
这是一个简单的例子:
<select data-bind="value: selectedItemValue, options: items, optionsValue: 'value', optionsText: 'text', optionsCaption: ''"></select>
<button type="button" data-bind="click: selectLast">Select Last</button>
<button type="button" data-bind="click: removeLastItem">Remove Last</button>
var viewmodel = function () {
var self = this;
this.items = ko.observableArray();
this.selectedItemValue = ko.observable(null);
this.selectLast = function () {
self.selectedItemValue(
self.items()[self.items().length - 1].value);
};
this.removeLastItem = function () {
self.items.pop();
};
this.items.push({
value: "item1",
text: "First item"
});
this.items.push({
value: "item2",
text: "Second item"
});
this.items.push({
value: "item3",
text: "Third item"
});
};
var vm = new viewmodel();
ko.applyBindings(vm);
实现我想要的行为的最佳方法是什么?
答案 0 :(得分:1)
在拉取请求中引入valueAllowUnset
:
#647 - 添加允许值绑定接受当前不在选项列表中的选定值的选项
这个旧的错误/功能已得到修复。因此,如果你升级你的小提琴至少使用 KO 3.1版,它就像你描述的那样工作:
答案 1 :(得分:0)
除了nemesv提到的内容之外,如果最后一个值与当前选定的值匹配,则可以简单地删除该值 -
this.removeLastItem = function () {
var lastItem = self.items()[self.items().length - 1];
if (self.selectedItemValue() === lastItem.value) {
self.selectedItemValue(null);
}
self.items.pop();
};
http://jsfiddle.net/guvbxor2/4/
基本上只是检查您是否要删除所选的选项,如果是,null