我有一个绑定(bind)到 Knockout 可观察数组的选择控件:
<select data-bind="event: { change: selectedProductOfferingChange }, options: $parent.productTypes, optionsText: 'text', optionsCaption: '-- Select --', value: selectedProductType, enable: !isReadOnly()"></select>
当选择更改时,我想运行一些代码,也许进行 AJAX 调用。如果不允许更改,我想取消更改并显示模式对话框。我无法订阅该属性,因为更改发生后将会触发。我需要新值来确定是否应取消更改。
我在 View 模型中尝试了以下操作,但尽管 View 模型上的属性 (selectedProductOffering) 未更新,但更改并未取消:
self.selectedProductOfferingChange = function (data, event) {
event.stopImmediatePropagation();
return false;
};
我可以在订阅中使用“beforeChange”选项吗?
self.selectedProductType.subscribe(function (previous) {
}, self, "beforeChange");
可以在这里取消更改吗?
最佳答案
经过一番思考,我得出的结论是:
self.selectedProductOfferingChange = function (data, e) {
// Do any checking here
if (confirm("OK to make this change ?")) { return; }
// This stops the viewmodel property from being updated
e.stopImmediatePropagation();
// Since the viewmodel property hasn't changed, force the view to update
self.selectedProductType.valueHasMutated();
};
此代码的问题在于它不允许您访问新值。计算将解决这个问题:
<select data-bind="options: $parent.productTypes, optionsText: 'text', optionsCaption: '-- Select --', value: computedSelectedProductType, enable: !isReadOnly()"></select>
self.computedSelectedProductType = ko.computed({
read: function () {
return self.selectedProductType();
},
write: function (value) {
// Do any checks here. If you want to revert to the previous
// value, don't call the following but do call:
// self.selectedProductType.valueHasMutated()
self.selectedProductType(value);
},
owner: self
});
关于javascript - 如何使用 Knockout 取消选择控件上的更改事件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21264769/