我有以下代码应该绑定(bind) observables 的 observableArray。
<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 是 available .
正如您在开头看到的,它绑定(bind)正确,并且在加载标签时绑定(bind)也有效。但问题是,当我修改输入中的元素时,绑定(bind)不会传播。我认为我错过了一些非常简单的东西,但找不到什么。
最佳答案
如果数组中直接有 ko.observable
对象,则需要使用 $rawData
而不是 $data
直接绑定(bind)到可观察对象本身而不是它们的值:
<span data-bind="foreach: langs">
<input data-bind="value: $rawData, valueUpdate: 'afterkeydown'"/>
</span>
演示 JSFiddle .
来自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.
关于javascript - 无法正确绑定(bind) observables 的 observableArray,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24785579/