Note that there are some explanatory texts on larger screens.

plurals
  1. PODatabinding with complex Knockout.js object
    text
    copied!<p>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.</p> <pre><code>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); </code></pre> <p>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.</p> <pre><code>&lt;table&gt; &lt;thead&gt; &lt;tr&gt; &lt;th&gt;Average&lt;/th&gt; &lt;th&gt;Frequency&lt;/th&gt; &lt;/tr&gt; &lt;/thead&gt; &lt;tbody data-bind="foreach: kjhkjh"&gt; &lt;tr&gt; &lt;td data-bind="text: $data.Average()"&gt;&lt;/td&gt; &lt;td data-bind="value: $data.Average"&gt;&lt;/td&gt; &lt;td data-bind="text: $data.Average"&gt;&lt;/td&gt; &lt;td data-bind="value: $data.Average()"&gt;&lt;/td&gt; &lt;td&gt;Test&lt;/td&gt; &lt;/tr&gt; &lt;/tbody&gt; &lt;/table&gt; </code></pre> <p>Since the <code>kjhkjh</code> object doesn't bind I would think it would throw an error, but it does not. Even when I put in <code>source.Data</code> it doesn't do anything; it only displays the static table and nothing binds to it.</p> <p>Update: In order to get the value from anything in Javascript I have to use some thing like this:</p> <pre><code>console.log(currentViewModel.source.Data()[11].Average()); </code></pre>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload