PDA

View Full Version : how to use setRootNode properly



nisuhw
12 Aug 2011, 9:27 PM
when i use setRootNode more than once for same tree, the grandchildren not updated.
this code illustrate the problem:


var myTreePanel = Ext.create('Ext.tree.Panel', {
title : 'Test Tree Panel',
width : 200,
height : 200,
root : {
text : 'root',
leaf : true
}
});


var tree1={
text:'item 1',
expanded:true,
children:[
{text:'item 1.1',expanded:true,
children:[
{text:'item 1.1.1',leaf:true},
{text:'item 1.1.2',leaf:true}
]},
{text:'item 1.2',expanded:true,
children:[
{text:'item 1.2.1',leaf:true},
{text:'item 1.2.2',leaf:true}
]},
]
};


var tree2={
text:'item 2',
expanded:true,
children:[
{text:'item 2.1',expanded:true,
children:[
{text:'item 2.1.1',leaf:true},
{text:'item 2.1.2',leaf:true}
]},
{text:'item 2.2',expanded:true,
children:[
{text:'item 2.2.1',leaf:true},
{text:'item 2.2.2',leaf:true}
]},
]
};


Ext.onReady(function() {
Ext.create('Ext.panel.Panel', {
renderTo : Ext.getBody(),
items : [ myTreePanel , {
xtype : 'button',
text : 'show tree1',
handler : function() {
myTreePanel.getStore().setRootNode(tree1);
}
},{
xtype : 'button',
text : 'show tree2',
handler : function() {
myTreePanel.getStore().setRootNode(tree2);
}
}]
})
})

i first click button 'show tree1' then click button 'show tree2' and click again button 'show tree1', the tree panel not update grandchildren of every item.
after i debug and see the content of tree1, the grandchildren is an empty array so i trick this using Ext.clone() to prevent lost of grandchildren of tree1.


myTreePanel.getStore().setRootNode(Ext.clone(tree1));

is there any better way to prevent tree1 from losing it's grandchild without clone the tree?

skirtle
13 Aug 2011, 12:58 PM
You don't even need tree2, you can reproduce this just by clicking the 'show tree 1' button twice. I agree this is pretty annoying. Seems to be caused by this line:


delete data[reader.root];

in Ext.data.TreeStore.onNodeAdded(). I don't understand this section of code well enough to comment but something doesn't feel right if it causes this issue.

One alternative way to avoid this issue is to create tree1 and tree2 afresh each time you need them. You could do something like this:


myTreePanel.getStore().setRootNode(createTree1());

...

function createTree1() {
return {
text: 'item1',
...
};
}

Obviously you'd want to put this function somewhere appropriate, depending on how many places it's used. At the very least you should namespace it.

One unrelated suggestion. There's no need to grab the store with myTreePanel.getStore().setRootNode(...);, you can just use myTreePanel.setRootNode(...);.