Reputation: 3
I have field A = A1 + A2
Field B = B1 + B2
Field C= A + B
When I change A1, A2, B1, B2
A,B,C working properly.
I tried manual change value field A or field B then hope field C = A + B
but not :(. Why ? and how to fix?
Please, help me! Thank you so much!
Here this my issue: http://jsfiddle.net/leoitviet/X8v6h/5/
Upvotes: 0
Views: 71
Reputation: 1015
here it is the jsfidle, note the subscribe function that detects any changes in the observable and make the operation, newval is the new value that you input, as the other pal said you cannot do both observable and computed. when changes in a1, a2 happens A is updated, when changes in A and B happens C is updated, also i recommend that you use self for namespacing all the variables. Vote me as acepted answer :)
var ViewModel = function () {
self = this;
self.A1 = ko.observable(0);
self.B1 = ko.observable(0);
self.A2 = ko.observable(0);
self.B2 = ko.observable(0);
self.A = ko.observable(0);
self.B = ko.observable(0);
self.C = ko.observable(0);
self.A1.subscribe(function(newval){
self.A(parseFloat(newval) + parseFloat(self.A2()))
});
self.A2.subscribe(function(newval){
self.A(parseFloat(self.A1()) + parseFloat(newval));
});
self.B1.subscribe(function(newval){
self.B(parseFloat(newval) + parseFloat(self.B2()))
});
self.B2.subscribe(function(newval){
self.B(parseFloat(self.B1()) + parseFloat(newval));
});
self.A.subscribe(function(newval){
self.C(parseFloat(newval) + parseFloat(self.B()))
});
self.B.subscribe(function(newval){
self.C(parseFloat(self.A()) + parseFloat(newval));
});
};
ko.applyBindings(new ViewModel());
http://jsfiddle.net/geomorillo/X8v6h/8/
Upvotes: 1
Reputation: 739
Your variables can be either ko.observable("") or ko.computed. But cannot be both. When you are changing A or B, it is not being observed. So no change in the value of C. When you are changing A1, A2, B1, B2, it is changing the value of A,B and C. This is an expected behavior.
Upvotes: 1