I have the following code which should bind observableArray of observables.
<button data-bind="click: loadTag">Upload</button>
<span data-bind="foreach: langs">
<input data-bind="value: $data, valueUpdate: 'afterkeydown'"/>
</span>
<div data-bind = "text: ko.toJS(langs)">
function vm() {
var self = this;
this.langs = ko.observableArray([]);
this.initiate = function(){
self.langs = ko.observableArray([]);
for (var i = 0; i < 4; i++){
self.langs.push(ko.observable('start'));
}
}
this.initiate();
this.loadTag = function(){
for (var i = 0; i < 4; i++){
self.langs()[i](i);
}
}
}
ko.applyBindings(new vm());
JS fiddle is available.
As you see in the beginning it binds correctly and also binding works when it loadTag. But the problem is that when I modify elements in input, binding does not propagate. I think that I miss something really simple, but can not find what.
If you directly have ko.observable
objects in your array you need to use $rawData
instead of $data
to bind directly to the observable objects themselves and not to their values:
<span data-bind="foreach: langs">
<input data-bind="value: $rawData, valueUpdate: 'afterkeydown'"/>
</span>
Demo JSFiddle.
From the 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.
来源:https://stackoverflow.com/questions/24281265/can-not-properly-bind-observablearray-of-observables