Reputation: 13
In Knockout I'm trying to have an entry field be auto-formatted, very similar to the example on this page under Writable Computed Observables:
http://www.knockmeout.net/2011/03/reacting-to-changes-in-knockoutjs.html
The problem I have is that if you enter values that get converted to the same thing (e.g. 1.00 and 1.0) then Knockout doesn't see that the value has changed and won't update the formatting (you can use the example on his page and see). I've created a hackjob solution where we change the field to something different and then change it back to trigger the update in Knockout, but I was wondering if someone had a more proper fix.
Thanks.
Upvotes: 1
Views: 1515
Reputation: 114792
There was a time that observables would always notify when written to, even when the value that you are writing has no changed. Since I believe KO 1.21, observables will suppress notifications when their actual value has not changed.
The simple solution is that you can call valueHasMutated
on an observable to ensure that notifications are sent.
A better way though to write the computed observable would be something like:
//writable computed to parse currency input
this.editPrice = ko.computed({
//return a formatted price
read: function() {
return viewModel.formatCurrency(this.price());
},
//if the value changes, make sure that we store a number back to price
write: function(newValue) {
var current = this.price(),
valueToWrite = viewModel.parseCurrency(newValue);
//only write if it changed
if (valueToWrite !== current) {
this.price(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) {
this.price.valueHasMutated();
}
}
},
owner: this
});
In this case, we would only write to the observable when the parsed value is different and we would only force notifications when the user entered a value that is different than the current value. This will cause the field to update even when a user enters a value that rounds toe current price.
Here is the updated sample: http://jsfiddle.net/rniemeyer/6A4aN/
Upvotes: 4