I have the following code:
function ViewModel() {
var self = this;
self.deckareax = ko.observable(0);
self.deckareay = ko.observable(0);
self.calculatedarea = ko.observable(20);
self.deckareax.subscribe(function () {
if (self.deckareax() == 0 || deckareay == 0) {
self.calculatedarea(0);
} else {
self.calculatedarea(self.deckareax() * self.deckareay());
}
}
);
self.deckareay.subscribe(function () {
console.log("deckareay " + self.deckareay())
if (self.deckareax() == 0 || self.deckareay() == 0) {
self.calculatedarea(0);
} else {
self.calculatedarea(self.deckareax() * self.deckareay());
}
}
);
self.deckareamxm = ko.computed({
read: function () {
return self.calculatedarea();
},
write: function (value) {
self.calculatedarea(value);
if ((self.deckareax() * self.deckareay(0)) != value) {
self.deckareax(0);
self.deckareay(0);
}
},
owner:self
});
}
;
ko.applyBindings(new ViewModel());
I want to be able to set the total area (deckareamxm) by either manually inputting or calcualting from entering deckareax * deckareay. If I enter a result and (deckareax * deckareay) doesn’t equal total deck area x and y should be cleared.
This pretty much works however if I enter total area it clears both but also clears itself. If I then enter again total area it stays. I think it may have got to complex. Any ideas?
This jsfiddle seems to do what you want. There were a couple other bugs but I primary fixed the problem by moving the
self.calculatedarea(value);to the bottom of the write function.