Tom Ortega II

Archive for July, 2006|Monthly archive page

Flex 2.0: Reopening a Tree after updating the dataProvider

In Flash*Flex*AS, Programming on July 28, 2006 at 4:16 pm

So, I’m completely stoked! I’ve figured out something that I think might actually be useful to the world in Flex! If you’ve worked with trees before, they’re fun except when you have to update their dataProvider. Then it’s not so fun because it collapses the tree and does not reopen it. Well, my friends, now it will. Check out this lil snippet of code. Copy it, paste it into FlexBuilder and press “Run”.

The two key elements of the tree are the openItems property and the render event. When used in conjuction with a boolean flag, you’re all set for keeping your tree open. Enjoy!

To see how trees normally act when changing dataProviders, delete the render event from the tree tag.

<?xml version=”1.0″ encoding=”utf-8″?>
<mx:Application xmlns:mx=”; layout=”vertical” creationComplete=”initFunc()”>
public var tempOpen:Object = new Object();
public var refreshSO:Boolean = false;

public var secondObject:Object = new Object();
public var tempObject:Object = new Object();
public var tempObject1:Object = new Object();
public var tempObject2:Object = new Object();
public var currentDP:String = “tempObject”;

private function initFunc():void

tempObject = new Object();
tempObject.path = “somepathvalue”+2;
tempObject.label = “Node”+2;
tempObject.componentType = “Type”+2;
tempObject.children = new Array();
tempObject1.label = “test3”;
tempObject1.children = new Array();
tempObject2.label = “test4”;
tempObject1.children[0] = tempObject2;
tempObject.children[0] = tempObject1;
secondObject = tempObject;


public function switchDP():void
tempOpen = testTree.openItems;
refreshSO = true;
if (currentDP == “tempObject”)
currentDP = “secondObject”;
testTree.dataProvider = secondObject;
currentDP = “tempObject”;
testTree.dataProvider = tempObject;

public function renderFunc():void
if (refreshSO)
refreshSO = false;
testTree.openItems = tempOpen;
<mx:Tree id=”testTree” render=”renderFunc()” width=”250″ dataProvider=”{tempObject}” labelField=”label” />
<mx:Button label=”Switch DP” click=”switchDP()”/>