Nov
23
2008

How to create a custom Event that will also pass an argument?

The most convenient way to communicate between objects is to use events. I'll show an example how to create custom event that will also carry a parameter.

Let's imagine some movieLoader class that waits for a call when and what movie to load. First I need to extend the Event class and create my new event.

In the first line I declare static const that would be an id of this event. This is the same as Keyboard.LEFT or Mouse.CLICK etc - to prevent typos and enable compile-time errors checking. Next I declare variable that will carry the argument passed with an event.

 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
import flash.events.Event;

public class CallMovieEvent extends Event
{
public static const CALL_MOVIE:String = "callAnotherMovie";

// This is variable that will be an event argument
public var whichMovie:uint;

public function CallMovieEvent(whichMovie)
{
//passing an event type to Event super class
super(CALL_MOVIE);
this.whichMovie = whichMovie;
}
}

 

Now, when the custom event is created, it's time to dispatch it from application. Let's imagine that user just clicked on Watch Movie button. MouseEvent handler function dispatches event with parameter which movie needs to be loaded. Movie number value was assigned to the button.

 

1
2
3
4
function onMouseClick():void
{
dispatchEvent(new CallMovieEvent(movieNumber));
}

 

Last step would be to set an event listener listening for the CallMovieEvent and associate handler function to load another movie.

 

1
2
3
4
5
6
7
8
//Listener in another object that loads the movies.
addEventListener("callAnotherMovie", loadAnotherMovie);

//and function that handles loading the movies
function loadAnotherMovie(e:CallMovieEvent):void
{
loadNewMovie(e.whichMovie); //whichMovie carries movieNumber value
}

 

More examples on how to pass an argument with events can be found here:
Link to learningactionscript2.com article

AS3 Tips