KO lazy loading example

The child nodes are lazy loaded (setTimeout here simulating an AJAX call).

by manchagnu

HTML

<script src="http://ajax.aspnetcdn.com/ajax/knockout/knockout-2.2.1.js"></script>
<ul id="nodes" data-bind='template: {name:"nodeTpl", foreach:nodes}'>
</ul>
 
<script id="nodeTpl" type="text/html">
    <li>
        <span data-bind='text:name, css:{clickable: children().length==0}'></span>
        <ul data-bind='template: {name:"nodeTpl", foreach:children}'></ul>
    </li>
</script>

CSS

ul{list-style-type: circle}
li{ margin-left: 1em}
.clickable{color: blue; text-decoration: underline; cursor: pointer}

JavaScript

var Node = function(name, children) {
    this.name = ko.observable(name);
    this.children = ko.observableArray(children || []);
};

var rootNode = new Node("Root");
var ViewModel = function () {
  var self = this;
  self.nodes = ko.observableArray([rootNode]);
};

ko.applyBindings(new ViewModel());

$("#nodes").on("click", ".clickable", function() {
  var context = ko.contextFor(this);
  var name = context.$data.name();
  //This is where you would make an AJAX call for the child nodes
  setTimeout(function () {
    context.$data.children([
      new Node(name+".1"), 
      new Node(name+".2"), 
      new Node(name+".3")
    ]);
  }, 1000);
  return false;
});