By default you are not able to pass multiple parameters to a event handler. So how am I allowed to do this?
In order to pass multiple parameters to your event handlers you need to extend the Event class and declare the optional parameters that you want to be passed along.
We create a simple Document class that will draw a square on the stage and this will allow us to dispatch custom events:
package {
import flash.display.Sprite;
import event.CustomEvent;
import flash.events.Event;
import flash.events.MouseEvent;
public class App extends Sprite
{
var square : Sprite ;
public function App()
{
init ( ) ;
}
private function init ( ) : void
{
//add the event listener to the Document class.
this.addEventListener(
CustomEvent.MOUSE_CLICK,
customEventHandler ) ;
// Draw a square on stage and add a mouseEvent
// that then will dispatch a custom event
square = drawSquare();
square.buttonMode = true;
square.addEventListener (
MouseEvent.CLICK,dispatchCustomEvent ) ;
addChild(square);
}
private function dispatchCustomEvent ( e : Event ) : void
{
dispatchEvent ( new CustomEvent (
CustomEvent.MOUSE_CLICK ,
"myParam1",
"myParam2",
3 ) ) ;
}
private function customEventHandler ( e :CustomEvent )
{
trace( "Param 1: " + e.param1 ) ;
trace( "Param 1: " + e.param2 ) ;
trace( "Param 1: " + e.param3 ) ;
}
private function drawSquare ( ) : Sprite
{
var square:Sprite = new Sprite();
square.graphics.beginFill(0x000000);
square.graphics.drawRect(100, 100, 100, 100);
square.graphics.endFill();
return square as Sprite;
}
}
}
Now we add the Custom Event Class
package event
{
import flash.events.Event;
public class CustomEvent extends Event
{
public static const MOUSE_CLICK : String = "mouseClick";
public var param1 : String ;
public var param2 : String ;
public var param3 : int ;
public function CustomEvent(
type : String,
param1 : String,
param2 : String,
param3 : int,
bubbles:Boolean = false,
cancelable:Boolean = false )
{
super ( type, bubbles, cancelable ) ;
this.param1 = param1;
this.param2 = param2;
this.param3 = param3;
}
override public function clone( ): Event
{
return new CustomEvent( type, param1, param2, param3,
bubbles, cancelable );
}
}
}
I didnt add details on what each line of code does, but please leave your questions in the comments and I will try to answer them.
Edit:
1. Formatting issues
2. implemented clone() method per
Robert
Penner's comment.
+