Can not properly bind observableArray of observables

梦想与她 提交于 2019-12-02 12:03:47

问题


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:


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!