You need to introduce a flag isCollapsed
on your TreeElement
which you can toogle from a click
binding event handler.
And based on that isCollapsed
you need to filter out your children
collection with a help of a computed observable:
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);
}
And you need to update your template with the click
binding handler and use the visibleChildren
instead of the children
collection:
<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>
Demo JSFiddle.