Sorting a Tree in Flex and Maintaining Open State on Refresh
I 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.
June 19th, 2009 at 5:37 am
Its nice one!
Thanks.
July 22nd, 2009 at 10:29 am
any idea how to sort the tree when you are using a hierarchical view as the dataprovider? I have a Grouping collection wrapped in an hierarchical view as the data provider for a my tree and I need to alpha sort the nodes. Can’t seem to get it to work.
November 12th, 2009 at 1:41 am
Thanks; really great work! One question; why did you put the tree inside a canvas, as opposed to being a standalone (Tree) component?
November 20th, 2009 at 4:24 am
Thanks, that saved me much work.