Can not properly bind observableArray of observabl

2019-03-01 20:37发布

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.

1条回答
我只想做你的唯一
2楼-- · 2019-03-01 21:03

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.

查看更多
登录 后发表回答