Sorting a Tree in Flex and Maintaining Open State on Refresh
Monday, December 8th, 2008I used Flex’s tree component in a content management system. The tree’s data provider was an ArrayCollection that received its data from a server call. The application would get the site map from the server whenever:
- a new article was saved
- an existing article was saved with a new parentID
- the user clicked the Refresh Site Map button
The site map had two issues: the articles were not sorted alphabetically, and the site map would lose its open state upon refresh.
I was able to solve both issues. Here is an example. You can view the full code.
You will first notice that the articles in the tree are not sorted alphabetically. If you check the Sort checkbox and click Refresh, it will simulate a call to the server where the data provider is replaced. The sort is performed in the setter for the data provider.
Also notice that the tree does not maintain its open state when its data provider is changed. Now check the Remember Open State checkbox and click Refresh. The tree maintains its open state.
The article objects in the tree have two properties: articleID and title. The articleID needs to be unique in order for the Remember Open State to work. It remembers its state by using recursion to cycle through all the tree items and saving an array of articleIDs that are open. When the new data provider is set, the nodes with articleIDs saved in the _openItems array are opened with the tree’s expandItem method.