What I'm trying to do is keep two text box's math in sync. The fields I'm working with is subtotal, taxTotal, tax rate, and sale total. What I want to happen is:
I didn't get very far with this, and I think it's because I keep thinking in terms of properties with backing fields (like in C#) and I'm having trouble trying to figure out the logic to keep everything bound and observable within the knockout framework (managing dirty states etc).
Does anyone have a solution for this? As far as I got led me to using pureComputed instead of computed. e.g.
this.subTotal = ko.observable(0.00);
this.taxRate = ko.pureComputed({
read: function(){
},
write: function(){
},
owner: this
});
this.taxTotal = ko.pureComputed({
read: function(){
},
write: function(){
},
owner: this
});
this.saleTotal = ko.computed(function(){
return this.subTotal ()+ this.taxTotal();
});
This was a fun one to figure out. One rule defines the read function for the taxTotal computed, the other defines the write function. The other two variables are just observables. I left out the 100 multiplier because it wasn't symmetric. It needs to be in both functions or neither.
var viewModel = (function () {
var subTotal = ko.observable(10),
taxRate = ko.observable(5);
var taxTotal = ko.computed({
read: function () {
return subTotal() * taxRate();
},
write: function (newValue) {
taxRate(newValue / subTotal());
}
});
return {
taxRate: taxRate,
taxTotal: taxTotal,
subTotal: subTotal
};
}());
ko.applyBindings(viewModel);
http://jsfiddle.net/ypsdh53q/
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With