Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

knockout compute sum

I receive data from a WCF and bind it to a table. I have been helped in this forum to add some compute fields and everything works perfectly. I'd like to add a total at the footer of this table. a simple version of my page could be seen at http://jsfiddle.net/qeUHd/3/ . Basically I'd like to learn how to add a field to my ViewModel that's the result of sum of Another field in my sample "Amount". Any help would be greatly appreciated. http://jsfiddle.net/qeUHd/3/

like image 647
Frenchi In LA Avatar asked Jun 07 '12 21:06

Frenchi In LA


2 Answers

In your fiddle, you're mapping your data set to self.model, so self.model is an observableArray. Since that was the case, I just needed to put together a computed value to get your total.

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 to bind to it.

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

You're doing things a little backward, but I assume it's due to the way you're receiving your data, so I dealt with it and moved on.

like image 100
deltree Avatar answered Sep 19 '22 12:09

deltree


While I would generally recommend and support putting these sorts of computed fields into the view model (as that is generally where they belong), there are times where you are working with data where it is difficult to add extra computed properties. An example would be if you are grouping your data within the view. In that case, you could 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>
like image 44
flipchart Avatar answered Sep 20 '22 12:09

flipchart