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 a custom event that will also carry a parameter.

I created the movieLoader class waiting for a call when and what movie needs to be loaded. To make everything working 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 a variable that will carry 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 a variable that will be an event argument
public var whichMovie:uint;

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

 

Now, when the custom event is created, it's time to dispatch it from your 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( CallMovieEvent.CALL_MOVIE , loadAnotherMovie);

//and function that handles movies loading
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 learningactionscript3.com article

 

AS3 Tips

I'm with Adobe - Facebook group