Need a copy of the tree store

2.8k Views Asked by At

ExtJS4

I've created a TreePanel as

var tree = Ext.create('Ext.tree.TreePanel', <some config>);
tree.store.setRootNode(treeJSON);

Now I want to create another tree with the same store data but different store objects. If I do this:

var tree1 = tree.cloneConfig(<separate listeners>);

Then, it creates a different tree. But still both are linked. When I collapse or expand one tree node, the corresponding node in the other tree also behaves similarly.

There is not cloneConfig property for store too so that I can duplicate it. I tried to recreate the store from the JSON for this tree.

var store2 = Ext.create('Ext.data.TreeStore', {store: treeJSON});
var tree1 = tree.cloneConfig({store: store2});

I thought store2 would be different from the trees store. But the problem was there since I was using the same treeJSON.

One thing I can do is to convert the JSON into string, decode it to create another JSON object and assign it to the new store. That would be different from the previous store. But there must exist a quick way for that.

How to create a duplicate tree with different store objects so that when I expand/collapse one node in a tree, it does not expand/collapse the same way in the other one?

2

There are 2 best solutions below

1
On

I have done something similar to this.

Parse your old tree to create a new tree

var root = existingTree.getRootNode ();
if (root) {
  var rootNode = this.getClonedTreeRoot(root);
  newTree.store.setRootNode (rootNode);
}


getClonedTreeRoot: function (node) {

  var me = this;
  var rootData;
  var childData = [];

  if (node.hasChildNodes ()) {
    var childNodes = node.childNodes;
    Ext.Array.each (childNodes, function (child) {
       if (child.get ('checked')) {
    childData.push (me.getClonedTreeRoot(child));           
       }        
    });
  }

  if (node.isLeaf ()) {
    rootData = {
        "text" : node.get ('text'),
        "leaf" : true,
        "expanded" : false,
        "children" : childData
    };
  } else {
    rootData = {
        "text" : node.get ('text'),
        "leaf" : false,
        "expanded" : true,
        "children" : childData
     };
   }

   return rootData;
}
0
On

Ext.data.NodeInterface has method "copy" with parameter "deep" but before ExtJs 4.1.3 deep cloning does not work. More detailed: they simply forgot to pass the "id" parameter when calling childNode.clone.

For people still using ExtJS < 4.1.3 use this to perform deep cloning of trees:

/**
 * Because of a bug in Ext.data.NoteInterface in ExtJs < 4.1.3
 * we have to do deep cloning.
 */
var clone = function(node) {
  var result = node.copy(),
      len = node.childNodes ? node.childNodes.length : 0,
      i;
  // Move child nodes across to the copy if required
  for (i = 0; i < len; i++)
    result.appendChild(clone(node.childNodes[i]));
  return result;
};

var oldRoot = store1.getRootNode(),
    newRoot = clone(oldRoot);

store2.setRootNode(newRoot);