我想要删除项目并折叠并打开它们。工作代码为here
var viewModel = {
treeRoot: ko.observableArray()
};
var TreeElement = function(name, children) {
var self = this;
self.children = ko.observableArray(children);
self.name = ko.observable(name);
}
var tree = [
new TreeElement("Russia", [
new TreeElement("Moscow")
]),
new TreeElement("Germany"),
new TreeElement("United States",
[
new TreeElement("Atlanta"),
new TreeElement("New York", [
new TreeElement("Harlem"),
new TreeElement("Central Park")
])
]),
new TreeElement("Canada", [
new TreeElement("Toronto")
])
];
viewModel.treeRoot(tree);
ko.applyBindings(viewModel);
像这样的HTML
<script id="treeElement" type="text/html">
<li>
<span data-bind="text: name"></span>
<ul data-bind="template: { name: 'treeElement', foreach: children }">
</ul>
</li>
</script>
<ul data-bind="template: { name: 'treeElement', foreach: $data.treeRoot }"></ul>
答案 0 :(得分:2)
您需要在isCollapsed
上引入一个标记TreeElement
,您可以从click
绑定事件处理程序中删除。
根据isCollapsed
,您需要借助计算的可观察量来过滤掉您的children
集合:
var TreeElement = function(name, children) {
var self = this;
self.children = ko.observableArray(children);
self.isCollapsed = ko.observable();
self.collapse = function() {
self.isCollapsed(!self.isCollapsed());
}
self.visibleChildren = ko.computed(function(){
if (self.isCollapsed())
return [];
return children;
});
self.name = ko.observable(name);
}
您需要使用click
绑定处理程序更新模板,并使用visibleChildren
代替children
集合:
<script id="treeElement" type="text/html">
<li>
<span data-bind="text: name, click: collapse"></span>
<ul data-bind="template: { name: 'treeElement', foreach: visibleChildren }">
</ul>
</li>
</script>
演示JSFiddle。