嘿我想从内部(嵌套)observableArray中删除一个项目如下,但删除按钮不起作用(对于内部的foreach项目)。从嵌套的observableArray中删除一个项目
http://jsfiddle.net/aDahT/1871/
HTML:
<h4>People</h4>
<ul data-bind="foreach: peoples">
<li>
Name at position <span data-bind="text: $index"> </span>:
<span data-bind="text: name"> </span>
<a href="#" data-bind="click: $parent.removePerson">Remove</a>
<ul data-bind="foreach:people">
<li>
<span data-bind="text: $data"></span>
<button data-bind="click: $parent.deletePerson">Remove</button>
</li>
</ul>
</li>
</ul>
<button data-bind="click: addPerson">Add</button>
脚本:
var Person = function(name, children){
var self = this;
self.name = name;
self.people = ko.observableArray(children);
self.deletePerson = function() {
alert(JSON.stringify(self));
self.people.remove(this);
}
}
function AppViewModel() {
var self = this;
self.peoples = ko.observableArray([
new Person('Bert', ['baa', 'bbb']),
new Person('Charles', ["caa", "cbb"])
]);
self.addPerson = function() {
alert(this);
self.peoples.push(new Person("New" ,["Daa", "Dbb"]));
}.bind(this);
self.removePerson = function() {
self.peoples.remove(this);
}
}
ko.applyBindings(new AppViewModel());
谁能帮助? 首先感谢。
谢谢!只是另一个问题,在这一行警报(JSON.stringify(self));为什么它显示名称的价值,但没有显示人的价值? – peanut 2014-10-07 05:59:46
Beacuse'JSON.stringify'只显示原始值,'people'是一个函数,因为它是一个可观察数组。你需要使用'ko.toJSON()'来获取人们的值,所以你需要写:'alert(ko.toJSON(self));' – nemesv 2014-10-07 06:01:57
谢谢,这是非常有意义的 – peanut 2014-10-09 03:32:03