Estimated Knockout Amount

I get data from WCF and bind it to a table. I was helped in this forum to add some fields of calculations, and everything works fine. I would like to add a total in the footer of this table. a simple version of my page can be seen at http://jsfiddle.net/qeUHd/3/ . Basically, I would like to learn how to add a field to my ViewModel so that the result of the sum of the other field in my example is β€œAmount”. Any help would be greatly appreciated. http://jsfiddle.net/qeUHd/3/

+6
source share
2 answers

In your script, you map your dataset to self.model, so self.model is an observable array. Since this was the case, I just needed to collect the calculated value to get the total amount.

http://jsfiddle.net/qeUHd/5/

self.total = ko.computed(function(){ var total = 0; for(var p = 0; p < self.model().length; ++p) { total += self.model()[p].Amount(); } return total; }); 

Then just make sure you are attached to it.

 <td data-bind="text: total"> 

You do something a little back, but I assume that this is due to how you get your data, so I worked on it and continued.

+11
source

While I usually recommend and support the transfer of these types of calculated fields to the presentation model (as is usually the case where they belong), there are times when you work with data where it is difficult to add additional calculated properties. For example, if you group your data in a view. In this case, you can still display your total, but move the calculation to the view:

 <td data-bind="text: $data.reduce(function(x,y) { return x + y.Amount(); }, 0)"></td> 
+1
source

Source: https://habr.com/ru/post/917566/


All Articles