Tree Issue
by WizKid81
HTML
<script src="http://code.jquery.com/jquery-2.1.4.min.js"></script>
<ul class="tree" data-bind="template: { name: 'itemTmpl', foreach: $data.hierarchyNodes }"></ul>
<script id="itemTmpl" type="text/html">
<li>
<button data-bind="click: getChildNodes">+</button>
<div data-bind="visible: hasChildren() == false" class="tree-spacer"></div>
<span data-bind="text: name" class="no_selection hierarchyNode"></span>
<ul class="tree" data-bind="template: { name: 'itemTmpl', foreach: $data.childNodes }, visible: expanded"></ul>
</li>
</script>
CSS
ul.tree {
list-style-type: none;
padding-left: 10px;
}
.hierarchyNode { border: 1px solid red; }
JavaScript
console.clear();
var hierarchyNode = function (parent) {
var self = this;
this.name = "Node Name";
this.hasChildren = ko.observable(true);
this.childNodes = ko.observableArray();
this.expanded = ko.observable(false);
};
hierarchyNode.prototype = {
name: null,
hasChildren: null,
childNodes: null,
getChildNodes: function (element, event) {
if (element.hasChildren() === true && element.childNodes().length === 0) {
element.childNodes.push(new hierarchyNode(element));
}
element.expanded(!element.expanded());
}
};
var hierarchyVM = function () {
var self = this;
self.hierarchyNodes = ko.observableArray();
self.selectItem = function () {};
};
var vm = new hierarchyVM();
vm.hierarchyNodes.push(new hierarchyNode(null));
console.log(vm.hierarchyNodes()[0]);
ko.applyBindings(vm);