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/
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.
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>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With