我有一个绑定到Knockout可观察数组的选择控件:
<select data-bind="event: { change: selectedProductOfferingChange }, options: $parent.productTypes, optionsText: 'text', optionsCaption: '-- Select --', value: selectedProductType, enable: !isReadOnly()"></select>
当选择被更改时,我想运行一些代码,或者进行AJAX调用。如果不允许更改,我想取消更改并显示模式对话框。我无法订阅该物业,因为在更改发生后将触发该物业。我需要新的值来确定是否应该取消更改。
我在viewmodel中尝试了以下操作,但是虽然viewmodel上的属性(selectedProductOffering)未更新,但未取消更改:
self.selectedProductOfferingChange = function (data, event) {
event.stopImmediatePropagation();
return false;
};
我可以使用&#34; beforeChange&#34;订阅选项?
self.selectedProductType.subscribe(function (previous) {
}, self, "beforeChange");
此处可以取消更改吗?
答案 0 :(得分:4)
经过一番思考,这就是我想出的:
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
});