Jul 07 2008
Event Listeners
Event Listeners:
Flash is based around event listeners. The basic idea of an event listener is pretty simple. Flash is constantly waiting for something to happen. As soon as the event happens, Flash runs the function that is connected to the listener.
Many cool things can be done with event listeners. Most user interaction is done though the Event Dispatcher class in Flash. There are tons of events in Flash but some of the most common ones for games are the KeyboardEvent and the MouseEvent.
Basic structure:
The basic structure of an event listener is pretty standard throughout Flash no matter what the event actually is.
Example:
object.addEventListener ( TypeOfEvent.ACTUAL_EVENT, functionToHandleEvent );
Object: This is the object you are putting the event on. It can be a variable, the stage, etc.
TypeOfEvent: The type of event ( Event, KeyboardEvent, MouseEvent, etc)
ACTUAL_EVENT: This is the thing you are actually listening for. I wrote it in all caps because they are always written in all caps.
functionToHandleEvent: This is your function that is going to be run once the event actually happens. It is called the handler function.
Example Handler:
function functionToHandleEvent ( EVENT:TypeOfEvent ) : ReturnType { Code to be executed }
The KeyboardEvent:
This script will register when a user pushes a key down and then traces out the key code number attached to that key.
Put this code in the first frame -
import flash.events.KeyboardEvent; stage.addEventListener ( KeyboardEvent.KEY_DOWN, keyDownHandler ); function keyDownHandler ( KBE:KeyboardEvent ) : void { trace ( "Key Down Code: " + KBE.keyCode ); }
Line 1: import the KeyboardEvent class so you can use it. You don’t have to do this if you are working on the timeline because Flash automatically imports it for you. If you are working in a class, you need to import it.
Line 3: Add the event listener to the stage to listen for when a key goes down. Set up the handler function called keyDownHandler
Line 5-8: The handler function. I named my parameter KBE. I am accessing the keyCode attribute of KBE. This is useful in games when you need to know the key the player is pushing down.
The MouseEvent:
import flash.events.MouseEvent; stage.addEventListener ( MouseEvent.CLICK, mouseClickHandler ); function mouseClickHandler ( ME: MouseEvent) : void { trace ( "Mouse X Position: " + ME.target.mouseX ); trace ( "Mouse Y Position: " + ME.target.mouseY ); }
Target - You can use the event.target method of Flash to get various things about what is ever happening. I use event.target all the time when I don’t know exactly what I am clicking on. That way I can write much more dynamic code.
As you can see the MouseEvent and KeyboardEvent setup are almost identical. This is almost the case with all event listeners in Flash.