Therefore the following steps need to be done:
- Find the component under the mouse cursor
- Dispatch a right click event on this this component
- Listen to right click events dispatch from a component or its sub components (event bubbling)
The first step can be accomplished using the following code:
private function findComponentBelowCursor():UIComponent
{
var globalPoint:Point = new Point( FlexGlobals.topLevelApplication.mouseX, FlexGlobals.topLevelApplication.mouseY );
var objects:Array = FlexGlobals.topLevelApplication.getObjectsUnderPoint( globalPoint );
for ( var i:int = objects.length - 1; i >= 0; i-- )
{
var o:Object = objects[ i ];
if( o is UIComponent )
{
return o as UIComponent;
}
if( o.hasOwnProperty( "parent" ) && o.parent is UIComponent )
{
return o.parent as UIComponent;
}
if( o.hasOwnProperty( "document" ) && o.document is UIComponent )
{
return o.document as UIComponent;
}
}
return null;
}The function getObjectsUnderPoint returns all DisplayObjects under the given point (globalPoint), which are searched for the topmost UIComponent.
If a UIComponent was found, a bubbling event is dispatched:
private function dispatchRightClickEvent( component:UIComponent ):void
{
var globalPoint:Point = new Point( FlexGlobals.topLevelApplication.mouseX, FlexGlobals.topLevelApplication.mouseY );
var localPoint:Point = object.globalToLocal( globalPoint );
object.dispatchEvent( new RightClickEvent( RightClickEvent.RIGHT_CLICK, true, true, localPoint.x, localPoint.y, object ));
}
Note that a custom RightClickEvent extending the MouseEvent was used in the sample code. Also it is very important to set bubbling to true so that parent components can listen to the event as well.
Here is a small sample application:
To view this page ensure that Adobe Flash Player version 10.0.0 or greater is installed.
If you right click into one of the lists, the RightClickEvent is dispatched on DefaultItemRenderer, bubbles up to the list which has event listener registered and is processed in the event handler.
It is also very important to properly clean up the menu every time you click outside of the menu or open another one. For this you can use a static manager class like the following:
package
{
import mx.controls.Menu;
import mx.core.FlexGlobals;
import mx.managers.PopUpManager;
public class RightClickMenuManager
{
private static var menu:Menu;
public static function showMenu( menu:Menu ):void
{
hideMenu();
menu.show( FlexGlobals.topLevelApplication.mouseX, FlexGlobals.topLevelApplication.mouseY );
RightClickMenuManager.menu = menu;
}
public static function hideMenu():void
{
if ( menu != null )
{
PopUpManager.removePopUp( menu );
}
}
}
}
No comments:
Post a Comment