我是 KnockoutJS 的新手,我认为它到目前为止是一个很棒的工具 :)!但是,我有一个关于计算可观察量的问题,如下所示。在 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/
我的问题是,当您输入相同的内容两次时,该值不会自行更新。例如:
第一步:输入25.1234,变成$25.12 第 2 步:再次输入 25.1234。现在什么也没有发生。
我的猜测是该值没有改变,因此它不会自行重新格式化。我可以知道如何解决这个问题吗?
谢谢!
最佳答案
这是 Knockout 中的一项优化,如果您将可观察对象设置为相同的值,它不会触发更改的事件。
因此,如果您想始终触发更改事件,则需要使用 valueHasMutated
方法手动触发它:
this.price(isNaN(value) ? 0 : value); // Write to underlying storage
this.price.valueHasMutated();
它本身不会修复您的代码,因为在 KO 3.0 中为 ko.computed
引入了另一个优化,因此如果计算值保持不变并且您计算的值也不会触发更改需要使用 .extend({notify: 'always'})
to force the notification of the subscribers.
所以完整的工作计算将如下所示:
this.formattedPrice = ko.computed({
read: function () {
return '$' + this.price().toFixed(2);
},
write: function (value) {
value = parseFloat(value.replace(/[^\.\d]/g, ""));
this.price(isNaN(value) ? 0 : value); // Write to underlying storage
this.price.valueHasMutated();
},
owner: this
}).extend({notify: 'always'});
演示 JSFiddle .
关于javascript - KnockoutJS 强制计算的 Observable 重新计算,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22372330/