JSFiddle - React, Tailwind, and code Playground
HTML
<button data-bind="click: newChild">NewNode</button>
<ul data-bind="template: { name: 'treeTemplate', foreach: children}">
</ul>
<script id="treeTemplate" type="text/html">
<li>
<input data-bind="value: name" />
<button data-bind="click: newChild">New Child</button>
<button data-bind="click: $parent.removeNode">Remove Node</button>
<button data-bind="click: $parent.copyNode">Copy Node</button>
<ul data-bind="template: { name: 'treeTemplate', foreach: children}"></ul>
</li>
</script>
CSS
ul {
padding: 6px;
margin: 2px;
}
JavaScript
var Node = function(name, children) {
var self = this;
self.name = ko.observable(name || 'NewNode');
self.children = ko.observableArray(
ko.utils.arrayMap(children || [], function(i) {
return new Node(i.name, i.children);
}));
self.newChild = function() {
self.children.push(new Node());
};
self.removeNode = function(node) {
self.children.remove(node);
};
self.copyNode = function(node) {
var cloneNode = ko.toJS(node);
self.children.push(new Node(cloneNode.name, cloneNode.children));
};
};
data = {
name: "root",
children: [
{
name: "Node1",
children: [
{
name: "child1",
children: []},
{
name: "child2",
children: []}
]},
{
name: "Node2",
children: []}
]
};
ko.applyBindings(new Node(data.name, data.children));