Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>I took your idea and made a <a href="http://jsfiddle.net/aCQNA/" rel="nofollow">working fiddle</a>, which behaves exactly how you described. I didn't want to try to sort yours out, sorry. It had a lot of stuff not directly related to your problem, and this solution is general enough that other people should be able to use it. If you need help adapting it, let me know.</p> <p>One thing to make note of is the clone function. Your copy function isn't deep, and will result in multiple nodes pointing to the same object. If you were to update a nodes value, it would propagate to its clones. Knockout provides a handy deep copy + unwrap observables with <code>ko.toJS</code>. Super useful.</p> <p>The JS:</p> <pre><code>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)); }; }; //Example data removed for brevity, see fiddle ko.applyBindings(new Node(data.name, data.children));​ </code></pre> <p>HTML:</p> <pre><code>&lt;button data-bind="click: newChild"&gt;NewNode&lt;/button&gt; &lt;ul data-bind="template: { name: 'treeTemplate', foreach: children}"&gt; &lt;/ul&gt; &lt;script id="treeTemplate" type="text/html"&gt; &lt;li&gt; &lt;input data-bind="value: name" /&gt; &lt;button data-bind="click: newChild"&gt;New Child&lt;/button&gt; &lt;button data-bind="click: $parent.removeNode"&gt;Remove Node&lt;/button&gt; &lt;button data-bind="click: $parent.copyNode"&gt;Copy Node&lt;/button&gt; &lt;ul data-bind="template: { name: 'treeTemplate', foreach: children}"&gt;&lt;/ul&gt; &lt;/li&gt; &lt;/script&gt; ​ </code></pre>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload