knockout compute sum

Frenchi In LA picture Frenchi In LA · Jun 7, 2012 · Viewed 12k times · Source

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/

Answer

deltree picture deltree · Jun 8, 2012

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.