Get Total Number of Childnodes (i.e. Deep-Children) of a TreeNode in ExtJS


***Getting Total Number of ChildNodes of a TreeNode (including at all levels of that TreeNode) in ExtJS***


Hi friends,


Here is a function which I had written to get number of all children of a TreeNode i.e. Both immediate (can also be obtained from TreeNode.childNodes.length) and all innerNodes (grand, grand-grand, etc.) till leaf-level i.e. till the end all the nodes.


As said, With TreeNode's property "childNodes" we get only first level child nodes array.
Consider if you want total number of child nodes under the given node, then following function will help you.

/**
  * Following Function recurses through all nodes under the given node,
  * and return an number
  * (e.g. If you pass a RootNode of a tree it will return how many total child nodes are there in the tree, (other than RootNode itself))
  */

  getNoOfAllChildNodes = function(Mynode){
 var totalNodesCount = 0;
 recurFunc = function(Node){
  if(Node.hasChildNodes() == false){
   return 0;
  }else if(Node.hasChildNodes()){
   totalNodesCount += Node.childNodes.length;
   Node.eachChild(recurFunc);
  }
 }

 if(Mynode.hasChildNodes() == false){
  return 0;
 }else if(Mynode.hasChildNodes()){
  totalNodesCount += Mynode.childNodes.length;
  Mynode.eachChild(recurFunc);
 }
 return totalNodesCount;
}

//How To Use - 
//Consider I have a AsyncTreeNode/TreeNode - and want to get total number of its all child nodes at all sub levels then

  var noOfAllChildNodes = getNoOfAllChildNodes(Node);
  //OR
  var noOfAllChildNodes = getNoOfAllChildNodes(Ext.getCmp(treePanelId).getNodeById(nodeId));
  //OR to get All nodes in a Tree
  var noOfAllChildNodes = getNoOfAllChildNodes(Ext.getCmp(treePanelId).getRootNode());

Fill free to ask if you have any difficulty or didn't understand anything...

Enjoy :-)

Comments

Popular posts from this blog

How to install / Configure Mantis For Apache-PHP-PostgreSQL combination

Modified ExtJS LOVCombo (List of Values) ux plugin - with select all, deselect all, text filter, bubble up and bubble down of selection

Randomized Probabilistic Bag of Objects Data-Structure using Map