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 t
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.
var vm = {
list: [
{ value: ko.observable('123') },
{ value: ko.observable('456') }
]
};
<ul data-bind='foreach: list'>
<li><input data-bind='value: value'/></li>
</ul>
<ul data-bind='foreach: list'>
<li><span data-bind='text: value'></span></li>
</ul>
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.