开发者

as3: how to emulate MouseEvents?

How can i "emulate" a MouseEvent, that has not been initiated by a button with a eventListener (e.g. just by a simple function call) and how can i pass variables into it to switch the event.types?

    public function myMouseEvent(event:MouseEven开发者_JAVA技巧t):void
    {
            switch (event.type)
            {
                case "mouseDown" :
                     trace(event.type)
                     break;

                case "mouseUp" :
                     trace(event.type)
                     break;
            }
    }

    myMouseEvent(null) // ? nothing happens...


1/ Basic

In your case you can call directly

myMouseEvent(new MouseEvent(MouseEvent.MOUSE_DOWN));

2/ Event

But you could do it in a more event-oriented manner.

eventDispatcher.dispatchEvent(new MouseEvent(MouseEvent.MOUSE_DOWN));

where eventDispatcher is the Sprite (or something else) you added your listener to.

3/ Proper Event

Since your can't access to all properties of the MouseEvent when you dispatch it like that, there is a cleaner way to do it:

public function myMouseEvent(event:Event):void
{
        switch (event.type)
        {
            case "mouseDown" :
                 trace(event.type)
                 break;

            case "mouseUp" :
                 trace(event.type)
                 break;
        }
}
eventDispatcher.addEventListener(MouseEvent.MOUSE_DOWN, myMouseEvent);
eventDispatcher.dispatchEvent(new Event(MouseEvent.MOUSE_DOWN));

All three may work!


The myMouseEvent( null ) call should actually give you an Exception as you're trying to access a parameter (type) on a null object.

To call this properly, you just need to create a MouseEvent object to pass to the function:

// add in any other params, like localX, stageX, etc
var m:MouseEvent = new MouseEvent( MouseEvent.MOUSE_DOWN );
this.myMouseEvent( m );

Alternatively, you can use dispatchEvent() if you want to go through the event system. Something like

this.stage.addEventListener( MouseEvent.MOUSE_DOWN, this.myMouseEvent );
this.dispatch( m ); // stage will catch this event
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜