这里是一个的jsfiddle,我相信修复您遇到的问题。
http://jsfiddle.net/JasonMore/gbhfT/6/
视图
<div data-bind="foreach: items, accordion: {}">
<h3>
<a href="#" data-bind="text: id"></a>
</h3>
<div>
<span data-bind="text: name"></span>
<div data-bind="foreach: items, accordion: {}">
<h3>
<a href="#" data-bind="text: id"></a>
</h3>
<div data-bind="text: name">
</div>
</div>
<button data-bind="click: add">Add Sub Item</button>
</div>
</div>
<button data-bind="click: add">Add Item</button>
<hr/>
的Javascript
ko.bindingHandlers.accordion = {
init: function(element, valueAccessor) {
var options = valueAccessor() || {};
setTimeout(function() {
$(element).accordion(options);
}, 0);
//handle disposal (if KO removes by the template binding)
ko.utils.domNodeDisposal.addDisposeCallback(element, function() {
$(element).accordion("destroy");
});
},
update: function(element, valueAccessor) {
var options = valueAccessor() || {};
$(element).accordion("destroy").accordion(options);
}
}
function Item(id, name, subItems) {
var self = this;
//properties
this.id = ko.observable(id);
this.name = ko.observable(name);
this.items = ko.observableArray(subItems);
//actions
this.add = function() {
self.items.push(new Item(4, "bar"));
};
}
var viewModel = {
items: ko.observableArray([
new Item(1, "one",
[
new Item(11, "one-one"),
new Item(12, "one-two")
]),
new Item(2, "two", []),
new Item(3, "three", [])
]),
add: function() {
viewModel.items.push(new Item(4, "foo"));
}
};
ko.applyBindings(viewModel);
你应该能够深刻的改变的foreach成模板,使这项工作正水平。 http://knockoutjs.com/documentation/template-binding.html
我希望这有助于!
杰森
你有没有找到一个解决问题了吗? – 2012-05-02 15:46:41