我的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);
Run Code Online (Sandbox Code Playgroud)
而html是
<div class='liveExample'>
<h2>People</h2>
<ul data-bind="foreach: people">
<li>
<div>
<span data-bind="text: name"> </span> has <span data-bind='text: children().length'> </span> children:
<a href='#' data-bind='click: addChild '>Add child</a>
</div>
<ul data-bind="foreach: children">
<li>
<input data-bind="value: $data" />
</li>
</ul>
</li>
</ul>
<div data-bind="text: outcode"></div>
<button data-bind='click: showcode'>out</button>
</div>
Run Code Online (Sandbox Code Playgroud)
在按"退出"按钮之前更改文本框值.
然后按"退出"按钮.结果是数组初始值,而不是新值.
请告诉我,我错过了什么.
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);}
Run Code Online (Sandbox Code Playgroud)
同样在foreach绑定中,如果你不想制作对象,你可以使用$ rawData进行双向绑定
<ul data-bind="foreach: children">
<li>
<input data-bind="value: $rawData" />
</li>
Run Code Online (Sandbox Code Playgroud)
更新了JsFiddle演示
| 归档时间: |
|
| 查看次数: |
162 次 |
| 最近记录: |