作者:邵元星_246 | 来源:互联网 | 2023-05-24 11:05
我的knockoutjs代码没有像我预期的那样工作.请访问http://jsfiddle.net/x0vdo9kk/1/上的代码.
// Define a "Person" class that tracks its own name and children, and has a method to add a new child
var Person = function(name, children) {
this.name = name;
this.children = ko.observableArray(children);
this.addChild = function() {
this.children.push("New child");
}.bind(this);
}
// The view model is an abstract description of the state of the UI, but without any knowledge of the UI technology (HTML)
var viewModel = {
people: [
new Person("Annabelle", ["Arnie", "Anders", "Apple"]),
new Person("Charles", ["Cayenne", "Cleopatra"])
],
outcode: ko.observable(),
showcode: function() {
this.outcode(this.people[0].children())
}
};
ko.applyBindings(viewModel);
而html是
在按"退出"按钮之前更改文本框值.
然后按"退出"按钮.结果是数组初始值,而不是新值.
请告诉我,我错过了什么.
1> Dmitriy Krup..:
observableArray跟踪数组中的哪些对象,而不是那些对象的状态,请参阅文档,因此您必须制作可观察的可观察数组.
var Person = function(name, children) {
this.name = name;
this.children = ko.observableArray(ko.utils.arrayMap(children,function(child){
return ko.observable(child);
}));
this.addChild = function() {
this.children.push(ko.observable("New child"));
}.bind(this);}
同样在foreach绑定中,如果你不想制作对象,你可以使用$ rawData进行双向绑定