New to Kendo UI for jQuery? Download free 30-day trial

Recursively Load Child Items of HierarchicalDataSource

Environment

Product Progress® Kendo UI® HierarchicalDataSource for jQuery

Description

In this article, you will find out how to recursively load all child data items of a HierarchicalDataSource.

Solution

  • Create a recursive function, which first checks if the current node is not loaded and respectively loads the node. Then, iterate over the collection that contains the children of that node and call the recursive function for each child.
function loadNode(node) {
    if(!node.loaded()) {
      node.load().then(function(){
            for (var i = 0; i < node.collection.length; i++) {
                loadNode(node.collection[i]);
            }
      });
    }
}
  • In a separate function, iterate over all parent data items from the view of the HierarchicalDataSource and call the recursive function for each parent.
function loadAllNodes() {
    for (var i = 0; i < dataSource.view().length; i++) {
        loadNode(dataSource.view()[i]);
    }
}
  • Call the second function in the fetch method of the HierarchicalDataSource to read the data items.
dataSource.fetch(function () {
    loadAllNodes();
});

The following example demonstrates the full implementation of the suggested approach:

<script>
    var dataSource = new kendo.data.HierarchicalDataSource({
            data: [
                {
                    text: "foo", 
                    id: "1",
                    hasChildren: true,
                    collection: [
                        { 
                            text: "bar", 
                            id: "2",
                            collection: [
                              { text: "foobar", id: "5" }
                            ]
                        }
                    ]
                },
                {
                    text: "foo2", 
                    id: "3",
                    hasChildren: true,
                    collection: [
                        { 
                            text: "bar2", 
                            id: "4" 
                        }
                    ]
                }
            ],
            schema: {
                model: {
                    id: "id",                 
                    children: "collection"
                }
            }
          });

    dataSource.fetch(function () {
        loadAllNodes();
        console.log(dataSource.get("2"));
        console.log(dataSource.get("4"));
    });

    function loadAllNodes() {
      for (var i = 0; i < dataSource.view().length; i++) {
            loadNode(dataSource.view()[i]);
        }
    }

    function loadNode(node) {
      if(!node.loaded()) {
        node.load().then(function(){
          for (var i = 0; i < node.collection.length; i++) {
                loadNode(node.collection[i]);
            }
        });
      }
    }   
  </script>

See Also

In this article