what is dispatchEvent in Flash AS3?

coderex picture coderex · Dec 6, 2009 · Viewed 41k times · Source

Hi all i want to know what is dispatchEvent in AS3. I didn't get any idea while Googling it. :( So please help me

Edit 1:

public static  const SET_VOLUME:String = "setVolume";

private function onclick(evt:MouseEvent):void {
            soundClip.scaleX = 0;
            dispatchEvent(new Event(SET_VOLUME));

        }

what does this means?? (

Answer

alecmce picture alecmce · Dec 7, 2009

An example might help? If you have Flash IDE, try this in your timeline:

var ball:Shape = new Shape();
ball.graphics.beginFill(0xFF0000);
ball.graphics.drawCircle(0, 0, 30);
ball.graphics.endFill();
addChild(ball);

stage.addEventListener(MouseEvent.MOUSE_MOVE, mouseMoveListener);
addEventListener("myCustomEvent", myCustomEventListener);

function mouseMoveListener(event:MouseEvent):void
{
    dispatchEvent(new Event("myCustomEvent"));
}

function myCustomEventListener(event:Event):void
{
    ball.x = stage.mouseX;
    ball.y = stage.mouseY;
}

This is code demonstrates how the addEventListener and dispatchEvent are counterparts. The MOUSE_MOVE event is dispatched internally, but you can dispatch your own events just like the MOUSE_MOVE using dispatchEvent.

What happens in this code is that a MOUSE_MOVE from the stage is detected, but rather than handle that in the mouseMoveListener, you dispatch another event (called myCustomEvemt) which is handled in the myCustomEventListener instead. It works just like the MOUSE_MOVE event, only you dispatched the event instead of the flash player.

Hope this helps.