Sasi Dhivya Sasi Dhivya - 1 month ago 5x
Javascript Question

How to create a tree structure in Knockout using a Knockout template?

I am working with

support and now creating tree structured
component. Here i will create the elements dynamically and there i want to bind the data to newly created elements.
Please check with the below code

<script src=""></script>

<script type="text/html" id="tree">
<li menuid="data bind with attr binding">
<span><a href="#" name="endnode"></span>
<ul data-bind="template: { name: 'tree', foreach: childNodes }">

below is my script

var viewModel = {
Mytree: ko.observable({
childNodes: [
id: 1,name:"node1",
childNodes: [ {id: 2, name:"node2", childNodes: [{id: 3,name:"node3", childNodes: [] }] } ]
id: 4,name:"node4",
childNodes: [ {id: 5,name:"node5", childNodes: [] } ]

ko.applyBindings(new viewModel.Mytree());

Now i want to append the
node names to to tree like below:

<span><a href="#" name="endnode" data-bind:""/></span>

<ul data-bind="template: { name: 'tree', foreach: childNodes }">

Can you please any one suggest me to achieve this


If you pass it the view model (you can use the $root syntax for this) you can just use "name" in the binding. The context will change as it goes down the tree ... there's a couple of other bits wrong - for one it's data-bind= (equals, not colon)

Try this template ...

      <script type="text/html" id="tree">
         <li menuid="data bind with attr binding">
            <a href="#" data-bind="text: name"></a>
            <ul data-bind="template: { name: 'tree', foreach: childNodes }" />

and use this to kick things off (note $root)

  <ul data-bind="template: { name: 'tree', data: $root }" />

this will give you ...

enter image description here