ActionScript 3 event handling tutorial: Difference between revisions

The educational technology and digital learning wiki
Jump to navigation Jump to search
 
(25 intermediate revisions by 2 users not shown)
Line 1: Line 1:
{{Under construction}}
{{Stub}}


== Overview ==
== Overview ==


; Learning goals:
; Learning goals:
: Learn how to understand the event handling model of Flash 9 (CS3) / ActionScript 3.
: Learn some essentials of the event handling model of Flash 9 (CS3) / ActionScript 3.
: Learn some Action Script '''3'''
: Learn some Action Script '''3''' (to be used within the Flash IDE)
: Use ActionScript within the Flash IDE.


;Prerequisites:
;Prerequisites:
:[[Flash CS3 desktop tutorial]]
:[[Flash CS3 desktop tutorial]]
:[[Flash drawing tutorial]]
:[[Flash drawing tutorial]]
:[[Flash button tutorial]]
:[[Flash components tutorial]]
:[[Flash components tutorial]]


;Moving on
;Moving on
: [[ActionScript 3 interactive objects tutorial]] (you also may directly read this piece)
: The [[Flash]] article has a list of other tutorials.
: The [[Flash]] article has a list of other tutorials.


Line 19: Line 20:
: This text should technical people get going and may not be good enough for self-learning beginners. It can be used as handout in a "hands-on" class. That is what [[User:Daniel K. Schneider|Daniel K. Schneider]] made it for...
: This text should technical people get going and may not be good enough for self-learning beginners. It can be used as handout in a "hands-on" class. That is what [[User:Daniel K. Schneider|Daniel K. Schneider]] made it for...
;Level
;Level
: It aims at beginners. However at some point you really should buy introductory book to ActionScript programming. We wont't be able to really teach you programming.
: It aims at Flash design beginners, '''not''' beginning ActionScript 3 programmers, although programmers can read this to get a quick overview before digging into a real documentation like [http://livedocs.adobe.com/flash/9.0/ActionScriptLangRefV3/ Adobe's Flash 9 reference manual]


; Learning materials
; Learning materials
Line 27: Line 28:
== Introduction ==
== Introduction ==


According to the [http://livedocs.adobe.com/flash/9.0/main/wwhelp/wwhimpl/common/html/wwhelp.htm?context=LiveDocs_Parts&file=00000397.html#wp124974 Flash CS3 documentation], retrieved 12:15, 7 September 2007 (MEST):
According to the [http://livedocs.adobe.com/flash/9.0/main/wwhelp/wwhimpl/common/html/wwhelp.htm?context=LiveDocs_Parts&file=00000397.html#wp124974 Flash CS3 documentation], retrieved 12:43, 7 September 2007 (MEST):
{{quotationbox|
{{quotationbox|
Every component broadcasts events when a user interacts with it. When a user clicks a Button, for example, it dispatches a <code>MouseEvent.CLICK</code> event and when a user selects an item in a List, the List dispatches an <code>Event.CHANGE</code> event. An event can also occur when something significant happens to a component such as when content finishes loading for a UILoader instance, generating an <code>Event.COMPLETE</code> event. To handle an event, you write ActionScript code that executes when the event occurs.
Every component broadcasts events when a user interacts with it. When a user clicks a Button, for example, it dispatches a <code>MouseEvent.CLICK</code> event and when a user selects an item in a List, the List dispatches an <code>Event.CHANGE</code> event. An event can also occur when something significant happens to a component such as when content finishes loading for a UILoader instance, generating an <code>Event.COMPLETE</code> event. To handle an event, you write ActionScript code that executes when the event occurs.
Line 36: Line 37:
=== Principles of event driven programming ===
=== Principles of event driven programming ===


; Events are broadcasted by the instance.
==== Events are detected by some object ====
That implies that you should give a name to each symbol instance. Otherwise your AS code can't find them.
 
* So before you code anything in ActionScript, click on the instance, open the parameters window and fill in '''label''' parameter.
Usually, events are broadcasted by an instance of an interactive object, typically a graphic on the screen that is a symbol instance. User interactions are, technically speaking, events generated by Flash objects. You then have to write code that can deal with these events. Firstly you must give a name to each symbol instance, users interact with. Otherwise your AS code can't find them.
* So before you code anything in ActionScript that deals with events generated by some user interaction with an object, click on this instance, open the parameters window and fill in '''label''' parameter.


This name must be legal:
This name must be legal:
* Start the label name with a letter
* Start the label name with a letter
* Do '''not use''' whitespaces or punctuation characters or dashes
* Do '''not use''' whitespaces or punctuation characters or dashes
==== ActionScript for Flash designers ====


; All ActionScript goes to the timeline
; All ActionScript goes to the timeline
AS2 also would allow you to attach code to instances. You can't do this.
* Always put AS code into a separate layer, e.g. call it "Action"
* Always put AS code into a separate layer, e.g. call it "Action"
* Note: AS2 also would allow you to attach code to instances. You can't do this.


For simple stuff, just put it in frame 1
; Action script code extends to frames in the same way as drawings
E.g. if you want the user to interact with buttons after the animation loads:
* Click on frame 1 of the "Action" layer
* Click on frame 1 of the "Action" layer
* Hit F9, then code :)
* Hit F9, then code :)


Code will only work within the frames the layer extends to. So if your code is supposed to be valid throughout the animation.
Code will only work within the frames the layer extends to. So if your code is supposed to be valid throughout the animation.
* Go to the last Frame
* Go to the last frame in your timeline
* Hit F5
* Hit F5


; Event registration
==== Event registration ====
For each event (user action or something else) you would like to intercept, you must register a so-called '''event listener'''.
 
For each event (user action or something else) you would like to intercept, you must register a so-called '''event listener''' function.


The syntax is the following:
The syntax is the following:
  addEventListener(''Type_of_event''.''Name_of_event'' Name_of_function_YOU_define);
  addEventListener(''Type_of_event''.''Name_of_event'', Name_of_function_YOU_define);
(Note: I am sure if all require the same arguments)


Example:
Example:
* Let's say you have a button instance.  In the parameters panel you named it ''hello_button''.
* Let's say you have a button instance.  In the parameters panel you named it ''hello_button''.
* If you want to tell the button to watch out for user clicks then you have to write something like to register the event.
* If you want to tell the button to watch out for user clicks then you have to write something like to register the event with a function (see below).
* So goto the ActionScript layer and hit F9. Then type:
* So goto the ActionScript layer and hit F9. Then type:


  hello_button.addEventListener(MouseEvent.CLICK, click_handler);
  hello_button.addEventListener(MouseEvent.CLICK, click_handler);


Programmers (only): You should be aware that a a component's events inherit from the parent classes. You also can remove a listener with the removeEventListener()
Programmers (only): You should be aware that a a component's events inherit from the parent classes. You also can remove a listener with the removeEventListener(). Also the correct explanation is "Registers an event listener object with an EventDispatcher object so that the listener receives notification of an event".


;The Event handler function
=== The event object ===
 
Let's recall that when an event happens, Flash will create an object that will be sent to the registered function. This object contains at least the following information:
 
: type - a string indicating the type of event
: target - the instance that sent the event (i.e. a reference to it).


The event handler function (also called a callback function) will be called by Flash as soon as the event happens.
Since target refers to an object you then can also extract information about the target, e.g. its label (if it has one).
The function you have to define '''yourself''' will receive the following:
* A single object that will contain information about the event type and the instance (e.g. the hello_button in our case).
* In other words, the function will know "what" happened and "where".


For this kind of information the event handler function can receive you must write code that deals with it, e.g. moves to playhead in the timeline to another frame.
==== The Event handler function ====


See below  ....
The event handler function (also called a callback function) will be called by Flash as soon as the event happens. Think a function as a kind of recipe that will do something with a given event.
This function that you have to define '''yourself''' will receive the following information:
* A single event object (just described before) that will contain information about the event type and the instance (e.g. the hello_button in our case).
* In other words, the function will know "what" happened and "where".


; Multiple events, multiple listeners
Now you must write some code that deals with it, e.g. moves to playhead in the timeline to another frame.


Note: about multiple events and multiple listeners:
* You can register multiple listeners to one instance.
* You can register multiple listeners to one instance.
* You can register the same listener to multiple instances.
* You can register the same listener to multiple instances.
=== The event object ===
The event object contains at least the following information:
; The Event type
: type - a string indicating the type of event
: target - the instance that sent the event (i.e. a reference to it).
Since target refers to an object you then can extract information from it, e.g. its label (if it has one).
=== The event handler function ===


After you registered an event handling function like
After you registered an event handling function like
Line 105: Line 104:


  function click_handler(event_object:MouseEvent) {
  function click_handler(event_object:MouseEvent) {
  /* Do something with this event */
}


  /* Do something with this event */
''event_object'' is a parameter name (we came up with) and that will contain a representation of the event and that includes a reference to the instance on which the user clicked, e.g. the 'hello_button'' in our case.
 
; A simple example
From the [[Flash button tutorial]]. When a user clicks on the "launch_button", then the ''launchRocket'' function is called. It will move the animation to Frame 2 and let it play.


  }
  launch_button.addEventListener(MouseEvent.CLICK,launchRocket);


''event_object'' is a variable name (we came up with) and that will contain the name of instance we defined, e.g. ''hello_button'' in our case.
function launchRocket(event:MouseEvent) { gotoAndPlay(2); }


; An example
; An example
Line 149: Line 155:
The function will receive an object that contains information about the event.
The function will receive an object that contains information about the event.


The first line below means the folloing
Let's now look at the first line. What does it mean ?
  function clickHandler(event:MouseEvent):void {
  function clickHandler(event:MouseEvent):void {


* Function is called clickHandler (we can give it any name we like)
* The function is called clickHandler (we can give it any name we like)
* Event object it will receive for processing is asssociated with ''event''. So ''event'' is a parameter that you can use as a variable in subsequent code.
* The event object it will receive for processing when something happens is associated with ''event''. In more technical terms ''event'' is a parameter that you can use as a variable in subsequent code.
* ''MouseEvent'' is the type of the variable ''event'' and we do have to declare this.
* ''MouseEvent'' is the type of the ''event'' variable and we should declare this.
* '':void'' means that the function will not return any information.
* '':void'' means that the function will not return any information.
Non-programmers: Just insert these last two elements the same way and don't worry.
Non-programmers: Just insert these last two elements the same way and don't worry.


''switch'' is a programming statement that is use to discriminate program flow. It's syntax is the following:
Note: Flash also allows Flash designers who typically just insert little bits of code to ignore typing, e.g. you just could write:
function clickHandler(event)
but this is considered bad practice, it makes your program less secure.
 
''switch'' is a programming statement that is use to organize program flow. In other words, we need to take different action for different user input. Its syntax is the following:
  switch (value) {
  switch (value) {
   case value_1 :
   case value_1 :
Line 169: Line 179:
   }
   }


So ''event.currentTarget.label'' means that we ask the event object ''event'' its current target (i.e. the button on which the user clicked) and from this it's label (i.e. what the user sees). This will allow us to figure out which button was clicked.
So ''event.currentTarget.label'' means that we ask the event object ''event'' its current target (i.e. the button on which the user clicked) and from this its label (i.e. what the user sees). This will allow us to figure out which button was clicked.
 
== Events obverview ==
 
All display objects with which you can interact can produce events: mouse, keyboard, and focus.
 
* [http://livedocs.adobe.com/flash/9.0/ActionScriptLangRefV3/flash/display/InteractiveObject.html InteractiveObject] (Adope ActionScript 3.0 Language and Components Reference)
 
 
=== List of events ===
 
Here is a short list of all (most?) events that can be generated by interactive objects with which a user can interact through mouse, keyboard, and the more general concept of focus. It also includes loading/modification events like animation entering a frame or an object being inserted to the stage.
 
For (very) technical information, consult in Adope ActionScript 3.0 Language and Components Reference: [http://livedocs.adobe.com/flash/9.0/ActionScriptLangRefV3/flash/display/InteractiveObject.html InteractiveObject] (see also its subclasses) and  [http://livedocs.adobe.com/flash/9.0/ActionScriptLangRefV3/flash/events/Event.html Event] (and subpages like [http://livedocs.adobe.com/flash/9.0/ActionScriptLangRefV3/flash/events/MouseEvent.html MouseEvent])
 
Here is a list of events and mouse/keyboard/focus event properties:
<table border="1">
<tr>
<th>Event</th>
<th>Description</th>
<th>Happens in target</th>
<th>Event property</th>
</tr>
<tr>
<td>activate</td>
<td>Dispatched when Flash Player gains operating system focus and becomes active.</td>
<td>EventDispatcher</td>
<td></td>
</tr>
<tr>
<td>added</td>
<td>Dispatched when a display object is added to the display list.</td>
<td>DisplayObject</td>
<td></td>
</tr>
<tr>
<td>addedToStage</td>
<td>Dispatched when a display object is added to the on stage display list, either directly or through the addition of a sub tree in which the display object is contained.</td>
<td>DisplayObject</td>
<td></td>
</tr>
<tr>
<td>click</td>
<td>Dispatched when a user presses and releases the main button of the user's pointing device over the same InteractiveObject.</td>
<td>InteractiveObject</td>
<td>MouseEvent.CLICK</td>
</tr>
<tr>
<td>deactivate</td>
<td>Dispatched when Flash Player loses operating system focus and is becoming inactive. </td>
<td>EventDispatcher</td>
<td></td>
</tr>
<tr>
<td>doubleClick</td>
<td>Dispatched when a user presses and releases the main button of a pointing device twice in rapid succession over the same InteractiveObject when that object's doubleClickEnabled flag is set to true.</td>
<td>InteractiveObject</td>
<td>MouseEvent.DOUBLE_CLICK</td>
</tr>
<tr>
<td>enterFrame</td>
<td>Dispatched when the playhead is entering a new frame.</td>
<td>DisplayObject</td>
<td></td>
</tr>
<tr>
<td>focusIn</td>
<td>Dispatched after a display object gains focus.</td>
<td>InteractiveObject</td>
<td>FocusEvent.FOCUS_IN</td>
</tr>
<tr>
<td>focusOut</td>
<td>Dispatched after a display object loses focus.</td>
<td>InteractiveObject</td>
<td>FocusEvent.FOCUS_OUT</td>
</tr>
<tr>
<td>keyDown</td>
<td>Dispatched when the user presses a key.</td>
<td>InteractiveObject</td>
<td>KeyboardEvent.KEY_DOWN</td>
</tr>
<tr>
<td>keyFocusChange</td>
<td>Dispatched when the user attempts to change focus by using keyboard navigation.</td>
<td>InteractiveObject</td>
<td>FocusEvent.KEY_FOCUS_CHANGE</td>
</tr>
<tr>
<td>keyUp</td>
<td>Dispatched when the user releases a key.</td>
<td>InteractiveObject</td>
<td>KeyboardEvent.KEY_UP </td>
</tr>
<tr>
<td>mouseDown</td>
<td>Dispatched when a user presses the pointing device button over an InteractiveObject instance in the Flash Player window.</td>
<td>InteractiveObject</td>
<td>MouseEvent.MOUSE_DOWN</td>
</tr>
<tr>
<td>mouseFocusChange</td>
<td>Dispatched when the user attempts to change focus by using a pointer device.</td>
<td>InteractiveObject</td>
<td>FocusEvent.MOUSE_FOCUS_CHANGE </td>
</tr>
<tr>
<td>mouseMove</td>
<td>Dispatched when a user moves the pointing device while it is over an InteractiveObject.</td>
<td>InteractiveObject</td>
<td>MouseEvent.MOUSE_MOVE</td>
</tr>
<tr>
<td>mouseOut</td>
<td>Dispatched when the user moves a pointing device away from an InteractiveObject instance.</td>
<td>InteractiveObject</td>
<td>MouseEvent.MOUSE_OUT</td>
</tr>
<tr>
<td>mouseOver</td>
<td>Dispatched when the user moves a pointing device over an InteractiveObject instance in the Flash Player window.</td>
<td>InteractiveObject</td>
<td>MouseEvent.MOUSE_OVER</td>
</tr>
<tr>
<td>mouseUp</td>
<td>Dispatched when a user releases the pointing device button over an InteractiveObject instance in the Flash Player window.</td>
<td>InteractiveObject</td>
<td>MouseEvent.MOUSE_UP</td>
</tr>
<tr>
<td>mouseWheel</td>
<td>Dispatched when a mouse wheel is spun over an InteractiveObject instance in the Flash Player window.</td>
<td>InteractiveObject</td>
<td>MouseEvent.MOUSE_WHEEL </td>
</tr>
<tr>
<td>removed</td>
<td>Dispatched when a display object is about to be removed from the display list.</td>
<td>DisplayObject</td>
<td></td>
</tr>
<tr>
<td>removedFromStage</td>
<td>Dispatched when a display object is about to be removed from the display list, either directly or through the removal of a sub tree in which the display object is contained.</td>
<td>DisplayObject</td>
<td></td>
</tr>
<tr>
<td>render</td>
<td>Dispatched when the display list is about to be updated and rendered.</td>
<td>DisplayObject</td>
<td></td>
</tr>
<tr>
<td>rollOut</td>
<td>Dispatched when the user moves a pointing device away from an InteractiveObject instance.</td>
<td>InteractiveObject</td>
<td>MouseEvent.ROLL_OUT </td>
</tr>
<tr>
<td>rollOver</td>
<td>Dispatched when the user moves a pointing device over an InteractiveObject instance.</td>
<td>InteractiveObject</td>
<td>MouseEvent.ROLL_OVER </td>
</tr>
<tr>
<td>tabChildrenChange</td>
<td>Dispatched when the value of the object's tabChildren flag changes.</td>
<td>InteractiveObject</td>
<td>Event.TAB_CHILDREN_CHANGE </td>
</tr>
<tr>
<td>tabEnabledChange</td>
<td>Dispatched when the object's tabEnabled flag changes.</td>
<td>InteractiveObject</td>
<td>Event.TAB_ENABLED_CHANGE</td>
</tr>
<tr>
<td>tabIndexChange</td>
<td>Dispatched when the value of the object's tabIndex property changes.</td>
<td>InteractiveObject</td>
<td>Event.TAB_INDEX_CHANGE </td>
</tr>
</table>
 
== Events decomposed ==
 
Each generated event contains different information, but some is inherited by all kinds of events:
 
=== All events ===
 
Technical note: The basic event class includes total (included inherited ) 8 properties, 26 constants and 13 public methods.
 
The most interesting property of an event is
* ''currentTarget'', the object that is actively processing the Event object with an event listener. E.g. the button on which a user clicked. You probably will use this one a lot.
 
Now let's look at mouse events. Flash defines 10 different types of mouse events (see the event overview table above). Each of these events contains extra information the may be useful. Let's have a look at the click event ojbect (as defined in the [http://livedocs.adobe.com/flash/9.0/ActionScriptLangRefV3/flash/events/MouseEvent.html#CLICK Adobe] reference manual.
This object conatins about 12 different properties that describe the event.
 
<table border="1">
<tr>
<th>Property</th>
<th>Value</th>
</tr>
<tr>
<td>bubbles</td>
<td>true</td>
</tr>
<tr>
<td>buttonDown</td>
<td>true if the primary mouse button is pressed; false otherwise.</td>
</tr>
<tr>
<td>cancelable</td>
<td>false; there is no default behavior to cancel.</td>
</tr>
<tr>
<td>ctrlKey</td>
<td>true if the Control key is active; false if it is inactive.</td>
</tr>
<tr>
<td>currentTarget</td>
<td>The object that is actively processing the Event object with an event listener.</td>
</tr>
<tr>
<td>localX</td>
<td>The horizontal coordinate at which the event occurred relative to the containing  sprite.</td>
</tr>
<tr>
<td>localY</td>
<td>The vertical coordinate at which the event occurred relative to the containing sprite.</td>
</tr>
<tr>
<td>shiftKey</td>
<td>true if the Shift key is active; false if it is inactive.</td>
</tr>
<tr>
<td>stageX</td>
<td>The horizontal coordinate at which the event occurred in global stage coordinates.</td>
</tr>
<tr>
<td>stageY</td>
<td>The vertical coordinate at which the event occurred in global stage coordinates.</td>
</tr>
<tr>
<td>target</td>
<td>The InteractiveObject instance under the pointing device. The target is notalways the object in the display list that registered the event listener. Use the currentTarget property to access the object in the display list that is currently processing the event.</td>
</tr>
</table>
 
What this technical documentation means is that we can extract extra information from the generated event object, e.g.
* if the user pressed the CTRL or SHIFT key
* where the target object sits, either relative to the stage or relative to a parent object.
* Of course, we also can extract the target itself, since a Mouse Click Event is a kind of general Event described above.
 
== Event propagation and bubbling ==
 
(to do, see http://www.adobe.com/devnet/actionscript/articles/event_handling_as3_03.html for now ...)
 
 
== Links ==
 
=== Tutorials ===
 
* [http://www.adobe.com/devnet/actionscript/articles/event_handling_as3.html Introduction to event handling in ActionScript 3.0] by Trevor McCauley, Adobe Developer Connection (good tutorial)
 
=== Important manual pages ===
 
These are almost impossible to understand for non programmers, but otherwise the documentation at Adobe is excellent.
 
* [http://livedocs.adobe.com/flash/9.0/ActionScriptLangRefV3/flash/display/InteractiveObject.html InteractiveObject]. This InteractiveObject class is the abstract base class for all display objects with which the user can interact, using the mouse and keyboard. Most Events are documented here. (Make sure to list also the inherited events).
 
* [http://livedocs.adobe.com/flash/9.0/ActionScriptLangRefV3/flash/events/Event.html Event]. The Event class is used as the base class for the creation of Event objects, which are passed as parameters to event listeners when an event occurs.
 
* [http://livedocs.adobe.com/flash/9.0/ActionScriptLangRefV3/flash/events/EventDispatcher.html EventDispatcher]. This is the page you should consult when you want to look up details for methods like addEventListener().
 
* [http://livedocs.adobe.com/flash/9.0/ActionScriptLangRefV3/class-summary.html Summary of All Flash Player Classes],


[[Category: Multimedia]]
[[Category: Multimedia]]
[[Category: Technologies]]
 
[[Category: Authoring tools]]
 
[[Category: Flash]]
[[Category: Flash]]
[[Category: Tutorials]]
[[Category:Flash tutorials]]

Latest revision as of 20:10, 14 October 2009

Draft

Overview

Learning goals
Learn some essentials of the event handling model of Flash 9 (CS3) / ActionScript 3.
Learn some Action Script 3 (to be used within the Flash IDE)
Prerequisites
Flash CS3 desktop tutorial
Flash drawing tutorial
Flash button tutorial
Flash components tutorial
Moving on
ActionScript 3 interactive objects tutorial (you also may directly read this piece)
The Flash article has a list of other tutorials.
Quality
This text should technical people get going and may not be good enough for self-learning beginners. It can be used as handout in a "hands-on" class. That is what Daniel K. Schneider made it for...
Level
It aims at Flash design beginners, not beginning ActionScript 3 programmers, although programmers can read this to get a quick overview before digging into a real documentation like Adobe's Flash 9 reference manual
Learning materials

Grab the various *.fla files from here:

http://tecfa.unige.ch/guides/flash/ex/action-script-3-intro/

Introduction

According to the Flash CS3 documentation, retrieved 12:43, 7 September 2007 (MEST):

Every component broadcasts events when a user interacts with it. When a user clicks a Button, for example, it dispatches a MouseEvent.CLICK event and when a user selects an item in a List, the List dispatches an Event.CHANGE event. An event can also occur when something significant happens to a component such as when content finishes loading for a UILoader instance, generating an Event.COMPLETE event. To handle an event, you write ActionScript code that executes when the event occurs.

Below a few basic principles

Principles of event driven programming

Events are detected by some object

Usually, events are broadcasted by an instance of an interactive object, typically a graphic on the screen that is a symbol instance. User interactions are, technically speaking, events generated by Flash objects. You then have to write code that can deal with these events. Firstly you must give a name to each symbol instance, users interact with. Otherwise your AS code can't find them.

  • So before you code anything in ActionScript that deals with events generated by some user interaction with an object, click on this instance, open the parameters window and fill in label parameter.

This name must be legal:

  • Start the label name with a letter
  • Do not use whitespaces or punctuation characters or dashes

ActionScript for Flash designers

All ActionScript goes to the timeline
  • Always put AS code into a separate layer, e.g. call it "Action"
  • Note: AS2 also would allow you to attach code to instances. You can't do this.
Action script code extends to frames in the same way as drawings

E.g. if you want the user to interact with buttons after the animation loads:

  • Click on frame 1 of the "Action" layer
  • Hit F9, then code :)

Code will only work within the frames the layer extends to. So if your code is supposed to be valid throughout the animation.

  • Go to the last frame in your timeline
  • Hit F5

Event registration

For each event (user action or something else) you would like to intercept, you must register a so-called event listener function.

The syntax is the following:

addEventListener(Type_of_event.Name_of_event, Name_of_function_YOU_define);

Example:

  • Let's say you have a button instance. In the parameters panel you named it hello_button.
  • If you want to tell the button to watch out for user clicks then you have to write something like to register the event with a function (see below).
  • So goto the ActionScript layer and hit F9. Then type:
hello_button.addEventListener(MouseEvent.CLICK, click_handler);

Programmers (only): You should be aware that a a component's events inherit from the parent classes. You also can remove a listener with the removeEventListener(). Also the correct explanation is "Registers an event listener object with an EventDispatcher object so that the listener receives notification of an event".

The event object

Let's recall that when an event happens, Flash will create an object that will be sent to the registered function. This object contains at least the following information:

type - a string indicating the type of event
target - the instance that sent the event (i.e. a reference to it).

Since target refers to an object you then can also extract information about the target, e.g. its label (if it has one).

The Event handler function

The event handler function (also called a callback function) will be called by Flash as soon as the event happens. Think a function as a kind of recipe that will do something with a given event. This function that you have to define yourself will receive the following information:

  • A single event object (just described before) that will contain information about the event type and the instance (e.g. the hello_button in our case).
  • In other words, the function will know "what" happened and "where".

Now you must write some code that deals with it, e.g. moves to playhead in the timeline to another frame.

Note: about multiple events and multiple listeners:

  • You can register multiple listeners to one instance.
  • You can register the same listener to multiple instances.

After you registered an event handling function like

hello_button.addEventListener(MouseEvent.CLICK, click_handler);

you then have to define this function. E.g. if we called our function click_handler we get the following template:

function click_handler(event_object:MouseEvent) {

 /* Do something with this event */

}

event_object is a parameter name (we came up with) and that will contain a representation of the event and that includes a reference to the instance on which the user clicked, e.g. the 'hello_button in our case.

A simple example

From the Flash button tutorial. When a user clicks on the "launch_button", then the launchRocket function is called. It will move the animation to Frame 2 and let it play.

launch_button.addEventListener(MouseEvent.CLICK,launchRocket);
function launchRocket(event:MouseEvent) { gotoAndPlay(2); }
An example

This is the copy/pasted example from the Flash components tutorial.

We first register an event handling function with five different buttons.

btn_rainbow.addEventListener(MouseEvent.CLICK, clickHandler);
btn_tecfa.addEventListener(MouseEvent.CLICK, clickHandler);
btn_bosses.addEventListener(MouseEvent.CLICK, clickHandler);
btn_my_computers.addEventListener(MouseEvent.CLICK, clickHandler);
btn_credits.addEventListener(MouseEvent.CLICK, clickHandler);

The function itself looked like this:

function clickHandler(event:MouseEvent):void {
	switch (event.currentTarget.label)
	{
		case "Rainbow" :
			gotoAndStop(2);
			break;
		case "TECFA" :
			gotoAndStop(3);
			break;
		case "Bosses" :
			gotoAndStop(4);
			break;
		case "My computers" :
			gotoAndStop(5);
			break;
		case "Credits" :
			gotoAndStop(6);
			break;
	}
}

The function will receive an object that contains information about the event.

Let's now look at the first line. What does it mean ?

function clickHandler(event:MouseEvent):void {
  • The function is called clickHandler (we can give it any name we like)
  • The event object it will receive for processing when something happens is associated with event. In more technical terms event is a parameter that you can use as a variable in subsequent code.
  • MouseEvent is the type of the event variable and we should declare this.
  • :void means that the function will not return any information.

Non-programmers: Just insert these last two elements the same way and don't worry.

Note: Flash also allows Flash designers who typically just insert little bits of code to ignore typing, e.g. you just could write:

function clickHandler(event)

but this is considered bad practice, it makes your program less secure.

switch is a programming statement that is use to organize program flow. In other words, we need to take different action for different user input. Its syntax is the following:

switch (value) {
  case value_1 :
    /* do something */
    break;
  case value_2 :
    /* do something */
    break;
  ....
  }

So event.currentTarget.label means that we ask the event object event its current target (i.e. the button on which the user clicked) and from this its label (i.e. what the user sees). This will allow us to figure out which button was clicked.

Events obverview

All display objects with which you can interact can produce events: mouse, keyboard, and focus.


List of events

Here is a short list of all (most?) events that can be generated by interactive objects with which a user can interact through mouse, keyboard, and the more general concept of focus. It also includes loading/modification events like animation entering a frame or an object being inserted to the stage.

For (very) technical information, consult in Adope ActionScript 3.0 Language and Components Reference: InteractiveObject (see also its subclasses) and Event (and subpages like MouseEvent)

Here is a list of events and mouse/keyboard/focus event properties:

Event Description Happens in target Event property
activate Dispatched when Flash Player gains operating system focus and becomes active. EventDispatcher
added Dispatched when a display object is added to the display list. DisplayObject
addedToStage Dispatched when a display object is added to the on stage display list, either directly or through the addition of a sub tree in which the display object is contained. DisplayObject
click Dispatched when a user presses and releases the main button of the user's pointing device over the same InteractiveObject. InteractiveObject MouseEvent.CLICK
deactivate Dispatched when Flash Player loses operating system focus and is becoming inactive. EventDispatcher
doubleClick Dispatched when a user presses and releases the main button of a pointing device twice in rapid succession over the same InteractiveObject when that object's doubleClickEnabled flag is set to true. InteractiveObject MouseEvent.DOUBLE_CLICK
enterFrame Dispatched when the playhead is entering a new frame. DisplayObject
focusIn Dispatched after a display object gains focus. InteractiveObject FocusEvent.FOCUS_IN
focusOut Dispatched after a display object loses focus. InteractiveObject FocusEvent.FOCUS_OUT
keyDown Dispatched when the user presses a key. InteractiveObject KeyboardEvent.KEY_DOWN
keyFocusChange Dispatched when the user attempts to change focus by using keyboard navigation. InteractiveObject FocusEvent.KEY_FOCUS_CHANGE
keyUp Dispatched when the user releases a key. InteractiveObject KeyboardEvent.KEY_UP
mouseDown Dispatched when a user presses the pointing device button over an InteractiveObject instance in the Flash Player window. InteractiveObject MouseEvent.MOUSE_DOWN
mouseFocusChange Dispatched when the user attempts to change focus by using a pointer device. InteractiveObject FocusEvent.MOUSE_FOCUS_CHANGE
mouseMove Dispatched when a user moves the pointing device while it is over an InteractiveObject. InteractiveObject MouseEvent.MOUSE_MOVE
mouseOut Dispatched when the user moves a pointing device away from an InteractiveObject instance. InteractiveObject MouseEvent.MOUSE_OUT
mouseOver Dispatched when the user moves a pointing device over an InteractiveObject instance in the Flash Player window. InteractiveObject MouseEvent.MOUSE_OVER
mouseUp Dispatched when a user releases the pointing device button over an InteractiveObject instance in the Flash Player window. InteractiveObject MouseEvent.MOUSE_UP
mouseWheel Dispatched when a mouse wheel is spun over an InteractiveObject instance in the Flash Player window. InteractiveObject MouseEvent.MOUSE_WHEEL
removed Dispatched when a display object is about to be removed from the display list. DisplayObject
removedFromStage Dispatched when a display object is about to be removed from the display list, either directly or through the removal of a sub tree in which the display object is contained. DisplayObject
render Dispatched when the display list is about to be updated and rendered. DisplayObject
rollOut Dispatched when the user moves a pointing device away from an InteractiveObject instance. InteractiveObject MouseEvent.ROLL_OUT
rollOver Dispatched when the user moves a pointing device over an InteractiveObject instance. InteractiveObject MouseEvent.ROLL_OVER
tabChildrenChange Dispatched when the value of the object's tabChildren flag changes. InteractiveObject Event.TAB_CHILDREN_CHANGE
tabEnabledChange Dispatched when the object's tabEnabled flag changes. InteractiveObject Event.TAB_ENABLED_CHANGE
tabIndexChange Dispatched when the value of the object's tabIndex property changes. InteractiveObject Event.TAB_INDEX_CHANGE

Events decomposed

Each generated event contains different information, but some is inherited by all kinds of events:

All events

Technical note: The basic event class includes total (included inherited ) 8 properties, 26 constants and 13 public methods.

The most interesting property of an event is

  • currentTarget, the object that is actively processing the Event object with an event listener. E.g. the button on which a user clicked. You probably will use this one a lot.

Now let's look at mouse events. Flash defines 10 different types of mouse events (see the event overview table above). Each of these events contains extra information the may be useful. Let's have a look at the click event ojbect (as defined in the Adobe reference manual. This object conatins about 12 different properties that describe the event.

Property Value
bubbles true
buttonDown true if the primary mouse button is pressed; false otherwise.
cancelable false; there is no default behavior to cancel.
ctrlKey true if the Control key is active; false if it is inactive.
currentTarget The object that is actively processing the Event object with an event listener.
localX The horizontal coordinate at which the event occurred relative to the containing sprite.
localY The vertical coordinate at which the event occurred relative to the containing sprite.
shiftKey true if the Shift key is active; false if it is inactive.
stageX The horizontal coordinate at which the event occurred in global stage coordinates.
stageY The vertical coordinate at which the event occurred in global stage coordinates.
target The InteractiveObject instance under the pointing device. The target is notalways the object in the display list that registered the event listener. Use the currentTarget property to access the object in the display list that is currently processing the event.

What this technical documentation means is that we can extract extra information from the generated event object, e.g.

  • if the user pressed the CTRL or SHIFT key
  • where the target object sits, either relative to the stage or relative to a parent object.
  • Of course, we also can extract the target itself, since a Mouse Click Event is a kind of general Event described above.

Event propagation and bubbling

(to do, see http://www.adobe.com/devnet/actionscript/articles/event_handling_as3_03.html for now ...)


Links

Tutorials

Important manual pages

These are almost impossible to understand for non programmers, but otherwise the documentation at Adobe is excellent.

  • InteractiveObject. This InteractiveObject class is the abstract base class for all display objects with which the user can interact, using the mouse and keyboard. Most Events are documented here. (Make sure to list also the inherited events).
  • Event. The Event class is used as the base class for the creation of Event objects, which are passed as parameters to event listeners when an event occurs.
  • EventDispatcher. This is the page you should consult when you want to look up details for methods like addEventListener().