Here is a jsFiddle demonstrating the following problem:
Given a foreach binding over a list of (observable) strings, the observables do not seem to update from changes to input tags bound inside the foreach. One would expect them to. Here's the example from the jsFiddle:
<ul data-bind='foreach: list'>
<li><input data-bind='value: $data'/></li>
</ul>
<ul data-bind='foreach: list'>
<li><span data-bind='text: $data'></span></li>
</ul>
var vm = { list: [ko.observable('123'), ko.observable('456')] };
ko.applyBindings(vm);
In the above example, one would expect that updating the input tags in the first list would cause the observables to update. Unfortunately they do not update as expected, as can be seen by the failure of the second list to reflect any changes to made to the first.
I verified that the list was not in fact being updated when the input elements are changed.
Interestingly, changes made to the observables are reflected in both lists (as one would expect). Namely, vm.list[1]("444")
will update the second element of both lists.
My recollection is that Knockout 2.0.0 did not have this issue, though I stand to be corrected. I did not find any documentation, Google or comments in the Knockout code that yielded any indication as to why this does not work or how to achieve the outcome expected.
Why does this not work as expected, and are there any workarounds that do not require changing the data structure?
I worked around this by using value: $parent.list[$index()]
, as seen in this jsFiddle. The new bindings looks like this:
<ul data-bind='foreach: list'>
<li>
<input data-bind='value: $parent.list[$index()]' />
</li>
</ul>
One could perhaps improve on this with a custom binding.
See also this related GitHub issue #708 for Knockout.js.
Update for Knockout 3.0:
Knockout now provides $rawData
:
<ul data-bind='foreach: list'>
<li><input data-bind='value: $rawData'/></li>
</ul>
creates a two-way binding as expected.
From the Binding Context documentation:
$rawData
This is the raw view model value in the current context. Usually this will be the same as $data, but if the view model provided to Knockout is wrapped in an observable, $data will be the unwrapped view model, and $rawData will be the observable itself.