读在淘汰赛可计算并不总是与扩展
问题描述:
发射,这可能是最简单的用小提琴http://jsfiddle.net/LkqTU/32190/读在淘汰赛可计算并不总是与扩展
来形容我有那么它舍入到两位数字,不允许非数字它有一个扩展可观察到的所谓的价格。
我有一个可写的计算可观察性,在它前面放一个美元符号。
但是,如果扩展器返回0.第二次发生$ 0不会返回到文本框(计算的可观察值),所以如果我在文本框中输入hello world(computed observable),价格正确报告0和格式化的价格显示$ 0。但是,如果我将其清除并再次输入hello world。这次价格仍然是0美元,但格式化的价格文本框显示你好世界(即使格式化的价格报告$ 0)。必须在某处丢失通知?
这里是代码。
ko.extenders.numeric = function(target, precision) {
//create a writable computed observable to intercept writes to our observable
var result = ko.pureComputed({
read: target, //always return the original observables value
write: function(newValue) {
var current = target(),
roundingMultiplier = Math.pow(10, precision),
newValueAsNum = isNaN(newValue) ? 0 : parseFloat(+newValue),
valueToWrite = Math.round(newValueAsNum * roundingMultiplier)/roundingMultiplier;
//only write if it changed
if (valueToWrite !== current) {
target(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) {
target.notifySubscribers(valueToWrite);
}
}
}
}).extend({
notify: 'always'
});
//initialize with current value to make sure it is rounded appropriately
result(target());
//return the new computed observable
return result;
};
function model() {
var self = this;
this.price = ko.observable('29.01').extend({
numeric: '2'
});
this.formattedPrice = ko.computed({
read: function() {
return '$' + this.price()
},
write: function(value) {
value = parseFloat(value.replace(/[^\.\d]/g, ""));
this.price(isNaN(value) ? 0 : value);
},
owner: this
});
}
var mymodel = new model();
$(document).ready(function() {
ko.applyBindings(mymodel);
});
答
什么似乎为我被延长formattedPrice
计算的变量总是通知和修改写入方法,只是在价值传递,而不是检查isNaN工作;您的扩展做到这一点无论如何,迫使一0时,使您的if (newValue !== current)
测试永远不会返回为NEWVALUE真实和电流将始终处于这种情况下0(NAN == 0 将通过检查!):
this.formattedPrice = ko.computed({
read: function() {
return '$' + this.price()
},
write: function(value) {
value = parseFloat(value.replace(/[^\.\d]/g, ""));
this.price(value); //just pass in nan or the value so the extender can check/notify if newValue !== current
},
owner: this
}).extend({
notify: 'always'
});