无法正确绑定 observableArray of observables [英] Can not properly bind observableArray of observables
问题描述
我有以下代码应该绑定 observableArray of 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 fiddle 可用.
JS fiddle is available.
正如您在开头看到的那样,它绑定正确,并且在 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
这是当前上下文中的原始视图模型值.通常这个将与 $data
相同,但如果提供给 Knockout 的视图模型被包裹在一个 observable 中, $data
将是展开的视图模型,并且 $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.
这篇关于无法正确绑定 observableArray of observables的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!