Note that there are some explanatory texts on larger screens.

plurals
  1. POHow to make changes to $data propagate back to Knockout's view-model?
    text
    copied!<p>I've got the following code using Knockout.js to display an array of bools as a series of checkboxes:</p> <pre><code>&lt;table&gt; &lt;tr data-bind="foreach: Array"&gt; &lt;td&gt;&lt;input type=checkbox data-bind="checked:$data"&gt;&lt;/td&gt; &lt;/tr&gt; &lt;tr data-bind="foreach: Array"&gt; &lt;td data-bind="text:$data"&gt;&lt;/td&gt; &lt;/tr&gt; &lt;/table&gt; &lt;button data-bind="click: toggle0"&gt;Toggle Element 0&lt;/button&gt; &lt;script&gt; var simpleModel = { "Array" : ko.observableArray([ko.observable(false), ko.observable(false), ko.observable(true)]), "toggle0" : function() { simpleModel.Array()[0](!simpleModel.Array()[0]()); } }; ko.applyBindings(simpleModel); &lt;/script&gt; </code></pre> <p>If you look at <a href="http://jsfiddle.net/tP9Dm/3/" rel="nofollow">http://jsfiddle.net/tP9Dm/3/</a>, you can see that, while the checkboxes respond to changes in the view-model, the view-model doesn't respond to changes in the checkboxes.</p> <p>According to <a href="https://groups.google.com/d/msg/knockoutjs/-dHpOg5ZBPI/1q4iqdTlKvUJ" rel="nofollow">https://groups.google.com/d/msg/knockoutjs/-dHpOg5ZBPI/1q4iqdTlKvUJ</a>, it looks like <code>$data</code> is unwrapped by the foreach loop, so <code>data-bind</code> doesn't know to use it to update the model.</p> <p>Clearly I can fix this by making the array contain objects instead of simple booleans, but that seems like it should be an unnecessary extra layer of indirection. Is there a simpler way to propagate changes back to the model?</p>
 

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