我是KnockoutJS的新手,并认为它是迄今为止一款出色的工具:)!不过,我有一个关于计算可观测量的问题,如下所示。在KnockoutJS页面http://knockoutjs.com/documentation/computedObservables.html处,有一个格式化价格的示例代码。代码如下。KnockoutJS强制计算Observable重新计算
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。现在没有反应。
我的猜测是该值没有改变,因此它没有重新格式化。我可以知道如何解决这个问题吗?
谢谢!
非常感谢!我曾看过这个,但没有意识到这是答案,哈哈。 – Wysie
还有一个问题,当我尝试以这种方式使用计算的observables时,我发现它通常会导致我的字段在我编辑它时自动更新。因此我需要使用hasFocus,然后使用简单的检查。但是,在上面的示例代码中,我发现在编辑它时,字段本身永远不会更新。这是为什么?我认为这是业主领域,但似乎并非如此......谢谢! – Wysie
我并不真正关注你的问题。这是如何使焦点来到图片?你可以创建一个新的小提琴来展示你现在面临的问题吗? – nemesv