I'm using knockoutjs to handle different events - one of them is i want to add thousand seperators to a price input f开发者_开发知识库ield.
So i subscribe a change event to my price field and that does some magic to add missing seperators and writes it back into the price field. The write back to the price field triggers a new change event and thus, i need a check to break the loop - which i do by asking if the value actually changed:
this.listingPriceFormatted.subscribe(function (newValue, model) {
var cleanValue = newValue.toString().replace(/\D/g, '');
$('#Price').val(cleanValue);
var outValue = MySite.Utilities.addThousandSeperator(cleanValue);
if (newValue != outValue) {
me.listingPriceFormatted(outValue);
}
});
I don't really like triggering the same event twice just to set the value once - is there any way i could write back to the field without triggering the event again, or am i doing this all wrong?
In this case, binding to a writable dependentObservable would probably be the right tool for the job. This will allow you to control how the field is read and set.
For example, if you have a listingPrice observable, then you could have a listingPriceFormatted writeable dependentObservable. You would bind your field to listingPriceFormatted. It would look like:
viewModel.listingPriceFormatted = ko.dependentObservable({
read: function() {
//add commas
return MySite.Utilities.addThousandSeperator(this.listingPrice());
},
write: function(newValue) {
//strip commas and store in listingPrice
this.listingPrice(MySite.Utilities.stripThousandSeperator(newValue));
}
}, viewModel);
This functionality was added after 1.12, so you would need to use a later copy of the code from GitHub. Hope this helps.
Also, at the end of this post, is an idea for encapsulating the observable and dependentObservable into one object that might be useful to you: http://www.knockmeout.net/2011/03/guard-your-model-accept-or-cancel-edits.html
精彩评论