Is it possible to create a recursive template only with knockout js?
I have a knockout object:
function FormElementNode(children, text, value) {
var self = this;
self.children = ko.observableArray(children);
self.text = ko.observable(text);
self.value = ko.observable(value);
}
children is an array of FormElementNode.
I want to draw it and it's children recursively in a hierarchy list nodes:
<ul>
<li>Parent text value:
Children:
<ul>
<li>Child1 text value</li>
<li>Child2 text value</li>
</li>
Thanks!
Yes KnockOut supports recursive templates so you can reference and render the same template inside the template.
An example html in your case would look like this:
Demo JSFiddle.
This post was a great help to me. I am always finding new ways to use knockout. I just wanted to add one useful modification which is doing exactly what nemesv proposed only using the ko.mapping plugin.
As demonstrated in this jsFiddle.
Recursive Custom Binding
Another solution, after reading that templates were slower I'm looking at going with recursive binding.
<ul data-bind="nestMe: name"></ul>
Having the opportunity to play with data before the recursion should come in handy.
JSFiddle
I think, I have a little better solution with no tree root. Please take a look:
http://jsfiddle.net/nonsense66/Bzekr/
Template:
Javascript:
Hope it helps!