分层ul列表崩溃与knockoutjs

时间:2014-05-13 07:06:44

标签: javascript jquery html css knockout.js

我想要删除项目并折叠并打开它们。工作代码为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>

1 个答案:

答案 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