AS3-101: Introduction to Events

– taterboy | June 14th, 2009

Filed under: ActionScript 101, Flash, Flex, Tutorials

ActionScript 3 101: Introduction to Events and the WooHoo Application.

Events are the most important concept to understand in ActionScript. After all, you can not have an interactive application without detecting user input. The new Event system in AS3 is much more powerful and consistent than in AS2, but it may seem like it requires a lot more lines of code. This is a very basic introduction to ActionScript 3 that demonstrates how to use Events and provides some tips for handling many events with less code.

1:Events – Hello World Application:
To build an interactive application we need to offer the user some components to interact with, once an interaction occurs, we need to reward them.

On my stage I have a button. I made this one, but you can use a button component if you like. We will give this button an instance name of “myButton”. Our first line of code will be:

?View Code ACTIONSCRIPT
myButton.addEventListener(MouseEvent.CLICK, clickHandler);

The illustration below show how events can be listened for within their own container or parent container if “bubbles” is set to true.

This adds an Event Listener to our button. The first argument in the listener is always the type of event. Flash has many built-in Event Classes that each contain unique event types. A few of the most common built-in Event Classes you will use are: TimerEvent, ProgressEvent, KeyboardEvent, MouseEvent and Event. You can look through the ActionScript reference guide for more information on each of these, their associated event types and what triggers them . In this example we will use an event type “CLICK” from the Event Class MouseEvent.

The second argument is the handler, this is a function with all of the instructions to reward our user for clicking the button. This is known ass the handler and usually should have the word “handler” in the name to help differentiate it from other non-event functions.

?View Code ACTIONSCRIPT
function clickHandler(event:MouseEvent):void{
 
}

The handler function receives an instance of the Event Class which provides information about the event and the object that triggered the event. More about this later.

The last step is to add the reward code to the handler.

?View Code ACTIONSCRIPT
var txt:TextField = new TextField();
txt.text = "HELLO WORLD";
addChild(txt);

Now save, publish and click on the button. “HELLO WORLD” should show up on screen. This is a very functional example, but not much of a reward.

2. Setup – WOOHOO Applicaiton:
Now that we have an Event and handler ,we can add a little more code and structure to make this example a little more exciting. As you can see from the image below, I added two movieclips, some instrucitons and a special WOOHOO movieclip. The woohoo clip is a simple animation with a stop action on the first frame.

3. Configuration:
I may over use variables, but I like to make code that is as transferable and editable as possible. So at the top we will list out all the hardcoded values and set them there instead of with-in the code itself. This is good practice because later we can easily find and update a value if I need to tweak something without rummaging though all the code. If this part is confusing, just skip it and hardcode the all the values normally.

For this app we have two movie Clips, we will listen for two built-in events then change a property of each movie clip. We will also monitor how many times each Event is triggered and dispatch a third custom event.

Our config area needs to contain all the starting property values for each movieclip and a couple variables to monitor each event count. We will also use a variable to limit each event count and fire our custom event.

?View Code ACTIONSCRIPT
var startAlpha:Number = 1		// starting "alpha" property of MovieClip1
var startY:Number = 	300;		// starting "y" propery of MovieClip2
var jump:int = 		20;		// amount each property jumps on event.
var clickCount:int = 	0;		// tracks click events
var keyCount:int = 		0;		// tracks keyboard events
var woohooCount:int = 	3;		// clicks to achieve "woohoo" status
var woohooNum:int = 	0;		// which woohoo animation to play - yes this is a little overboard.

4. Event listeners:

?View Code ACTIONSCRIPT
myButton.addEventListener(MouseEvent.CLICK, clickHandler); // on button click call the clickHandler function.
stage.addEventListener(KeyboardEvent.KEY_UP,keyHandler); // on keyboard press call the keyHandler function.
addEventListener("WOO_HOO",woohooHandler); // custom event, when dispatched, call the woohooHandler function.

The first two events are built-in events, the last is a custom event we will use when our click count reaches “woohoo” status.

5. Handlers:

?View Code ACTIONSCRIPT
function clickHandler(event:MouseEvent):void{
	//adjust alpha of movieclip 1 to fade out on each click
	movieClip1.alpha -= jump;
 
	//increase count
	clickCount ++;
 
	//check if count has reached "woohoo" status
	if(clickCount == woohooCount){
		//dispatch our custom "WOO_HOO" event. 
		woohooNum = 1;
		dispatchEvent(new Event("WOO_HOO"));
	}
}
 
function keyHandler(event:KeyboardEvent):void{
	//adjust y of movieclip 2 upward on each click
	movieClip2.y -= jump;
 
	//increase count
	keyCount ++;
 
	//check if count has reached "woohoo" status
	if(keyCount == woohooCount){
		//dispatch our custom "WOO_HOO" event. 
		woohooNum = 2;
		dispatchEvent(new Event("WOO_HOO"));
	}
}
 
function woohooHandler(event:Event):void{
	// play woo hoo animation (combine "woohoo" string with woohooNum
	// to match the correct frame label
	woohoo.gotoAndPlay("woohoo" + woohooNum);
 
	// reset everything
	clickCount = 0;
	keyCount = 0
	movieClip1.alpha = startAlpha;
	movieClip2.y = startY;
}

Demo:
Press the myButton and/or buttons on the keyboard to see the effects of the events. You may have to click into the Flash area to get the keyboard events to register.

Get Adobe Flash player

Download Source Here

6. Wrap Up:
All Events have a “bubbles” property which controls how far your event will be dispatched. If it is set to false or left blank as we did in this exampl, only listeners in the same class or movieclip can hear when the event is dispatched. Set it to true if your dispatching an event from within a nested movieClip or class to allow the event to be heard all the way up to the root level of your application.

Example of bubbling all the way to a parent or root level.

?View Code ACTIONSCRIPT
dispatchEvent(new Event("WOO_HOO", true));

Here is an Example how to write your own custom events to contain extra properties you may need in your Application application.

7. Tips:
I mentioned earlier about the instance of the Event that event handlers receive when an event is dispatched. You can find descriptions and property names for each bit of information the event contains. One of the properties is target, which is a reference to the object that triggered the event. Here are a couple of examples of using event information to do more event handling with less code.

7-A. Many Event Types With One Handler:
Some may get the impression that every event listener needs it own unique handler. This is an example how to handle click, rollover and rollOut events with one handler.

?View Code ACTIONSCRIPT
myButton.addEventListener(MouseEvent.CLICK, mouseHandler);
myButton.addEventListener(MouseEvent.MOUSE_OVER, mouseHandler);
myButton.addEventListener(MouseEvent.MOUSE_OUT), mouseHandler);
 
funciton mouseHandler(event:MouseEvent):void{
	trace("Event Type: " + event.type);
 
	if(event.type == "MouseOver"){
		trace("MOUSE_OVER mouse event");
	}
	else if(event.type == "MouseOut"){
		trace("MOUSE_OUT mouse event");
	}
	else{
		trace("CLICK mouse event");
	}
}

Note: Each Event Class does need it’s own handler, for instance a mouseEvent handler will not be able to receive the event.type or event .target of a KeyboardEvent.

7-B. Many Buttons With One Handler:
Instead of creating an event handler for each button, we can use the buttons name to handle multiple buttons with one handler.

?View Code ACTIONSCRIPT
myButton1.addEventListener(MouseEvent.CLICK, mouseHandler);
myButton2.addEventListener(MouseEvent.CLICK, mouseHandler);
myButton3.addEventListener(MouseEvent.CLICK, mouseHandler);
 
funciton mouseHandler(event:MouseEvent):void{
	trace("Event Target: " + event.target.name);
 
	if(event.target.name == "myButton1"){
		trace("myButton1 - CLICK");
	}
	else if(event.target.name == "myBUtton2"){
		trace("myButton2 - CLICK");
	}
	else{
		trace("myButton3 - CLICK");
	}
}

7-C. Keyboard Events will Not Register Until the Flash Player Has Focus:
You will notice the Keyboard Event listener is tied to the stage to receive maximum exposure. If the Flash content is part of an html page you can insure the Flash Player has focus by asking the user to click a “start button” in the Flash Area to start the application.

7-D. Keyboard Events Contain keyCode And charCode Values:
Use the keyCode property for the type of key pressed and charCode for the value of each key pressed. charCode will return a different value for an uppercase “A” and a lowercase “a”. Add this line to the keyboard event handler.

?View Code ACTIONSCRIPT
trace(event.keyCode + " | " + event.charCode);

Learn How To Build Your Own Custom Events Here »

Technorati Tags: , , , , , , , ,

| 3 Comments » | facebook:

3 Comments »

  1. [...] 06/15/2009 This tutorial will… Original post:  Sliding menu with actionscript 3 and TweenLite AS3-101: Introduction to Events – taterboy.com 06/15/2009 ActionScript 3 101: Introduction to Events and the WooHoo Application. [...]

    Pingback by Video | Enjolt.com | Innovate for Success — June 15, 2009 @ 4:15 am

  2. Thanks for that :) dispatchEvent was exactly what I was searching for… I think…

    Comment by Manuel Graf — July 24, 2009 @ 4:03 am

  3. Let me know if you need any more help.

    Comment by taterboy — July 24, 2009 @ 6:36 am

RSS feed for comments on this post. TrackBack URL

Leave a comment

*