I am having issues getting a foreach loop to work in KnockOut.js and even when I try to get the code to throw an error it does not. It is as if it is not trying to bind to the table at all.
var History = function (data) {
this.Average = ko.observable(data.Average);
this.Count = ko.observable(data.Count);
};
var DataSource = function (data) {
var convertData = function (array) {
return $.map(data.Data, function (option) {
return new History;
});
};
this.Data = ko.observableArray(this.convertData());
return {
'Data': this.Data
};
};
var dataMappingOptions = {
create: function (options) {
return new DataSource(options);
}
};
var dataModel = function () {
this.source = ko.mapping.fromJS({ 'Data': [], 'Percentage': 0 });
};
currentViewModel = new dataModel();
ko.applyBindings(currentViewModel);
I have stripped out a lot of the complexity of this as everything else works. Basically I am using the Knockout.Mappings to map an AJAX response to these objects and adding functions for computed fields. Here is the HTML that seems to ignore everything I do; it will display, but nothing binds to it.
<table>
<thead>
<tr>
<th>Average</th>
<th>Frequency</th>
</tr>
</thead>
<tbody data-bind="foreach: kjhkjh">
<tr>
<td data-bind="text: $data.Average()"></td>
<td data-bind="value: $data.Average"></td>
<td data-bind="text: $data.Average"></td>
<td data-bind="value: $data.Average()"></td>
<td>Test</td>
</tr>
</tbody>
</table>
Since the kjhkjh object doesn’t bind I would think it would throw an error, but it does not. Even when I put in source.Data it doesn’t do anything; it only displays the static table and nothing binds to it.
Update:
In order to get the value from anything in Javascript I have to use some thing like this:
console.log(currentViewModel.source.Data()[11].Average());
The error I was having was caused by the placement of my Knockout model on the page. Once I moved the script tag referring to the JS file below where the table was it worked correctly. That is why all of the page worked except for this excerpt. This is in part because I have it as a global variable as multiple parts of the page and several JS files needed to reference it.
That being said Stockedout did point out some ways I was able to improve the code.