javascriptdatabaseknockout.jsknockout-2.0knockout-templating

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


I am working with Knockout support and now creating tree structured UI 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="https://cdnjs.cloudflare.com/ajax/libs/knockout/3.2.0/knockout-min.js"></script>

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

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 bindable node names to to tree like below:

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

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

Can you please any one suggest me to achieve this


Solution

  • 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">
                <span>&nbsp;</span>
                <a href="#" data-bind="text: name"></a>
                <ul data-bind="template: { name: 'tree', foreach: childNodes }" />
             </li>
         </script>
    

    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