I'm new to KnockoutJS and think it's a great tool so far :)! However, I've a question regarding computed observables, and it's as follows. On the KnockoutJS page at http://knockoutjs.com/documentation/computedObservables.html, there's a sample code for formatting the price. The code is as follows.
HTML
<p>Enter bid price: <input data-bind="value: formattedPrice"/></p>
And the 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());
I've also copied the code and put a jsFiddle here: http://jsfiddle.net/wDvxw/
My issue is that the value does not update itself when you enter the same thing twice. For example:
Step 1: Enter 25.1234, it becomes $25.12 Step 2: Enter 25.1234 again. Now nothing happens.
My guess is that the value did not change and thus it doesn't reformat itself. May I know how I can go about fixing this?
Thanks!