【发布时间】:2014-04-17 19:34:51
【问题描述】:
我是 KnockoutJS 的新手,我认为到目前为止它是一个很棒的工具 :)!但是,我有一个关于计算的 observables 的问题,如下所示。在http://knockoutjs.com/documentation/computedObservables.html 的KnockoutJS 页面上,有一个用于格式化价格的示例代码。代码如下。
HTML
<p>Enter bid price: <input data-bind="value: formattedPrice"/></p>
还有 JS:
JS
function MyViewModel() {
this.price = ko.observable(25.99);
this.formattedPrice = ko.computed({
read: function () {
return '$' + this.price().toFixed(2);
},
write: function (value) {
// Strip out unwanted characters, parse as float, then write the raw data back to the underlying "price" observable
value = parseFloat(value.replace(/[^\.\d]/g, ""));
this.price(isNaN(value) ? 0 : value); // Write to underlying storage
},
owner: this
});
}
ko.applyBindings(new MyViewModel());
我也复制了代码并在这里放了一个jsFiddle:http://jsfiddle.net/wDvxw/
我的问题是,当您输入两次相同的内容时,该值不会自行更新。例如:
第 1 步:输入 25.1234,变为 $25.12 第 2 步:再次输入 25.1234。现在什么都没有发生。
我的猜测是该值没有改变,因此它不会重新格式化自己。我可以知道如何解决这个问题吗?
谢谢!
【问题讨论】: