Why are my knockouts calculated, observables not working?

I can not calculate the value of this work. Any input would be appreciated.

I get values โ€‹โ€‹for my prices from the server.

var pModel = function () { var self = this; self.prices = ko.observable({ "ID": 1,"Price1": 12,"Price2": 12}); self.Total = ko.computed(function () { var total = 0; total = self.prices().Price1 + self.prices().Price2; return total; }); }; var VModel = new pModel(); ko.applyBindings(VModel); 
 <script src="https://cdnjs.cloudflare.com/ajax/libs/knockout/2.1.0/knockout-min.js"></script> <form action='/someServerSideHandler'> <table> <thead> <tr>Prices</tr> </thead> <tbody id="calc"> <tr> <td>Price 1</td> <td> <input data-bind='value: prices().Price1' /> </td> </tr> <tr> <td>price 2</td> <td> <input data-bind='value: prices().Price2' /> </td> </tr> <td>TOTAL</td> <td> <span data-bind="text: $root.Total"></span> </td> </tbody> </table> </form> 
+4
source share
2 answers

Your prices variable is observable, but its members are not. Override this as follows:

  self.prices = ko.observable({ ID: ko.observable(1), Price1: ko.observable(12), Price2: ko.observable(12) }); 

Now it almost works, but if you change the values, it converts them to strings, so the total of 18 and 12 will be 1812 ! We will need to turn these lines into numbers.

  self.Total = ko.computed(function () { var price1 = parseFloat(self.prices().Price1()); var price2 = parseFloat(self.prices().Price2()); return price1 + price2; }); 

You must be tuned!

+3
source

You are a little confused: every value that other parts of your review model should respond to, if they have changed, should be observable. In your case, you have a "price" object that is observable, but the properties of this object (such as "Price 1" and "Price 2") are not observable. This means that your calculated observable will be updated only if the entire object placed in the "prices" is replaced with a new value.

So, just make these values โ€‹โ€‹invisible:

 var pModel = function () { var self = this; self.prices = { "ID": 1, // IDs normally do not change so no observable required here "Price1": ko.observable(12), "Price2": ko.observable(12) }; self.Total = ko.computed(function () { return +self.prices.Price1() + +self.prices.Price2(); }); }; 

Demo: http://jsfiddle.net/Jjgvx/3/

+3
source

All Articles