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:
HTML
<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>
Javascript
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: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
:creates a two-way binding as expected.
From the Binding Context documentation:
Every data object used in the default knockout bindings will always be unwrapped. So you are essentially binding to the value of the items in the list, not the observable as you are expecting.
Observables should be properties of an object, not a replacement of the object itself. Set the observables as a property of some object so this doesn't happen.