曾经有一段时间,observables 在写入时总是会通知,即使您正在写入的值没有改变。由于我相信 KO 1.21,当实际值没有改变时,可观察对象会抑制通知。
简单的解决方案是您可以调用valueHasMutated
observable 以确保发送通知。
编写计算的 observable 的更好方法是:
//writable computed to parse currency input
this.editPrice = ko.computed({
//return a formatted price
read: function() {
return viewModel.formatCurrency(this.price());
},
//if the value changes, make sure that we store a number back to price
write: function(newValue) {
var current = this.price(),
valueToWrite = viewModel.parseCurrency(newValue);
//only write if it changed
if (valueToWrite !== current) {
this.price(valueToWrite);
} else {
//if the rounded value is the same, but a different value was written, force a notification for the current field
if (newValue !== current) {
this.price.valueHasMutated();
}
}
},
owner: this
});
在这种情况下,我们只会在解析的值不同时写入 observable,并且只会在用户输入的值与当前值不同时强制通知。即使用户输入与当前价格四舍五入的值,这也会导致字段更新。
这是更新的示例:http: //jsfiddle.net/rniemeyer/6A4aN/