Wednesday, February 14, 2007

Flex tree's with a context menu

Recently on the flexcoders list a question was posed regarding how to get the item that was 'right-clicked on' when dealing with a tree. There are a few steps to follow if you plan to implement a context menu that is dynamic based on individual tree items.

First, you need to use the itemRollOver event of the <mx:Tree> component to track the last item that was rolled over, and save it to a variable for later use. Then when the ContextMenuEvent.MENU_SELECT event is triggered, you will refer back to this variable as it holds a reference to the itemRenderer and therefore the data you need access to.

You can view an example here and view the code here...

4 comments:

JPK said...

beware ! rollover event continues to be launched after right button pressed and during the exploration of the context menu by the mouse. The result is a shift of the selected node in your tree !! If somebody knows the solution, thanks

Michael Imhoff said...

Hi JPK,

I just took a look at what you mentioned and have been unable to replicate the issue you point out. Can you provide more details of what you're running into?

Have a good day,
Michael

Anonymous said...

The issue will happen while you use firefox.

dangerOp said...

Hi,

This is a nice little example. I extended it a little bit by having the right-click also cause the tree to make the item under the mouse become selected.

I wanted to do this because it's the behavior of most desktop applications, e.g. windows explorer, and a lot of our users were getting confused with our flex app. I used the line:

myTree.selectedItem = _lastTreeItem.itemRenderer.data;

... in the contextMenuTriggered function.

Thanks,
KaJun