Tag Archives: mousevent

Cloning a MouseEvent

I’ve seen the question of how to dispatch a MouseEvent through code, but i’ve never seen it answered. I figured it out so i’ll share it with your here.

Let’s say you have a BallSprite class and a RectSprite class (BallSprite being a graphic of a ball…..etc). And i want a MouseEvent.Click on an instance of BallSprite to trigger a MouseEvent.Click on an instance of RectSprite

Give the instance of BallSprite access to the instance of RectSprite. Note how i dispatch a clone of the click on the BallSprite instance. Now any MouseEvent.Click listeners on RectSprite instance will be triggered.

[cc lang=”actionscript”]
package myClasses
{
import flash.display.Sprite;
import flash.display.DisplayObject;
import flash.events.MouseEvent;
public class Ball extends Sprite
{

private var _rect:Rect;
public function Ball(dispObj:DisplayObject)
{
_rect = dispObj:DisplayObject;
this.addEventListener(MouseEvent.CLICK,clickHandler);
// add a graphic to our Ball instance
this.graphics.beginFill(0x00ff);
this.graphics.drawCircle(50,50,50);
this.graphics.endFill();
}

private function clickHandler(e:MouseEvent):void {
trace(‘ball click, now rect dispatches click’);
_rect.dispatchEvent(e.clone());
}
}
}

[/cc]