无法正确绑定observableArray的可观察对象 [英] Can not properly bind observableArray of observables
问题描述
我有以下代码,它们应该绑定observableArray的observables。
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小提琴是可用。
正如您在开头看到的那样,它正确绑定,并且绑定在loadTag时也能正常工作。但问题是当我修改输入中的元素时,绑定不会传播。我想我错过了一些非常简单但却无法找到的东西。
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.
推荐答案
如果你直接拥有 ko.observable
您需要使用 $ rawData
而不是 $ data
的数组中的对象直接绑定到可观察对象本身而不是它们的值:
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>
演示 JSFiddle 。
来自文档:
$ rawData
$rawData
这是当前上下文中的原始视图模型值。通常这个
将与 $ data
相同,但是如果提供给Knockout
的视图模型包含在一个observable中, $ data
将是展开的视图模型,
和 $ rawData
将是observable本身。
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.
这篇关于无法正确绑定observableArray的可观察对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!