Thursday, September 25, 2008

Flex Tree Component Bug

Yesterday I encountered a bug with setting the selectedIndex of the Flex tree component. The default behavior for dropping an item onto a Tree, or any List control, is to drop items in between the items currently in the list. I, however, wanted to drop items onto the items currently in the list. One common way to do this is to set a handler for the dragOver event of the Tree and in this handler call calculateDropIndex on the Tree and set the Tree's selectedIndex equal to this result. This gives some nice visual feedback and lets you easily get access to the element in the Tree at the target drop location.

The problem I encountered manifests itself when a new item is added to the Tree. In particular, if the dataProvider of the Tree is an Array, there seems to be an off-by-one error when dragging over the elements of the Tree after an element has been added to the underlying Array. If you use an ArrayCollection as the dataProvider for the Tree, everything works fine.

In the demo below, try dragging any of the elements in the two Trees over the other elements in the Tree. All seems to work. Now reset the demo, and click the "Add Item" button for the Tree on the right (the one backed by the ArrayCollection.) Note that it continues to work as expected. Now try to do the same thing with the Tree on the left. After doing a fresh reset and clicking "Add Item", good luck trying to drop something onto the element with label "5".

After doing a small amount of debugging, I've come to the conclusion that the calculateDropIndex method is always returning the right value, but that setting selectedIndex is not correctly finding the right element in the Tree.

You can check out the source for this here.



1 comment:

hakon said...

I encountered the exact same error today. The drop index seems fine, but setting the selectedIndex equal to the drop index results in another item being selected. Have you found any solution?