I have managed to find examples online of single calculated items, but does anybody have an example of a simple knockout grid with a field that is calculated based upon the value of other fields?
EDIT : Here is some code that I have written, but I am pretty sure I am going about it the wrong way so far :
<script type="text/javascript" src="@Url.Content("~/Scripts/knockout-2.1.0.js")"></script>
<script type="text/javascript">
function QBRatingsViewModel() {
var self = this;
var baseUri = '@ViewBag.ApiUrl';
self.qbratings = ko.observableArray();
this.Interception = ko.observable();
this.Gain = ko.observable();
this.CalculatedRating = ko.computed(function() {
return this.Interception() * this.Gain();
}, this);
$.getJSON("/api/qbrating", self.qbratings);
}
$(document).ready(function () {
ko.applyBindings(new QBRatingsViewModel());
});
</script>
<div style="padding-left: 10px;">
<div id="divQBRatings" style="padding-left: 3px; width: 750px;">
<table class="grid" cellspacing="0" cellpadding="0" id="QBRatingsGrid">
<tr class="gridheader"><td style="width: 30px;">Id</td><td width="10" /><td style="width: 40px;">Season</td><td width="10" /><td style="width: 70px;">Team </td><td width="10" /><td style="width: 130px;">Completion </td><td width="10" /><td style="width: 190px;">Gain </td><td width="10" /><td style="width: 30px;">Touchdown </td><td width="10" /><td style="width: 30px;">Interception </td><td width="10" /><td style="width: 30px;">Rating</td><td width="10" /><td></td></tr>
<tbody data-bind="foreach: qbratings" class="grid">
<tr>
<td><span style="width: 30px;" data-bind="text: $data.Id"></span></td>
<td width="10" />
<td><span style="width: 40px;" data-bind="text: $data.Season"></span></td>
<td width="10" />
<td><span style="width: 130px;"data-bind="text: $data.TeamName"></span></td>
<td width="10" />
<td><span style="width: 190px;" data-bind="text: $data.Completion"></span></td>
<td width="10" />
<td><span style="width: 190px;" data-bind="text: $data.Gain"></span></td>
<td width="10" />
<td><span style="width: 190px;" data-bind="text: $data.Touchdown"></span></td>
<td width="10" />
<td><span style="width: 190px;" data-bind="text: $data.Interception"></span></td>
<td width="10" />
<td><span style="width: 190px;" data-bind="text: $data.CalculatedRating"></span></td>
</tr>
</tbody>
</table>
</div>
</div>
I don’t know if your calculated property is related to item or whole view model. If it’s related to item you should do something like this:
If it’s related to whole model you should use $parent instead of $data: