What is Software? | What is Education? | What is Technology? | What is Research? | What is Wi-Fi? | What is Communication? | What is Customer Service?

Free SEO Tutorials & Help

Tutorials:   Adobe Flash   Adobe Photoshop   CorelDRAW   SEO  

Site Map

Website Development | Cable & Broadband Magazine | Solutions for Higher Education | Auction Anything Online

Adobe Flash Help & Tutorials

 Back to Topics

 

How to Handle Component Events in Flash

Handling Component Events

About scope in listeners

Using listeners to handle events

Delegating events

Using listener objects

About the event object

Using the handleEvent callback function

Using the on() event handler

Using listener functions

 

Handling Component Events

TOP

Every component has events that are broadcast when a user interacts with it (for example, the click and change events) or when something significant happens to the component (for example, the load event). To handle an event, you write ActionScript code that executes when the event occurs.

Each component broadcasts its own set of events. This set includes the events of any class from which the component inherits. This means that all components, except the media components, inherit events from the UIObject and UIComponent classes, because they are the base classes of the version 2 architecture. To see the list of events a component broadcasts, see the component's entry and its ancestor classes' entries in the Components Language Reference.

Using listeners to handle events

TOP

The version 2 component architecture has a broadcaster/listener event model. (A broadcaster is sometimes also referred to as a dispatcher.) It is important to understand the following key points about the model:

  • All events are broadcast by an instance of a component class. (The component instance is the broadcaster.)

  • A listener can be a function or an object. If the listener is an object, it must have a callback function defined on it. The listener handles the event; this means the callback function is executed when the event occurs.

  • To register a listener to a broadcaster, call the addEventListener() method from the broadcaster. Use the following syntax:

    componentInstance.addEventListener("eventName", listenerObjectORFunction);

  • You can register multiple listeners to one component instance.

    myButton.addEventListener("click", listener1);

    myButton.addEventListener("click", listener2);

  • You can register one listener to multiple component instances.

    myButton.addEventListener("click", listener1);

    myButton2.addEventListener("click", listener1);

  • The handler function is passed an event object.

    You can use the event object in the body of the function to retrieve information about the event type, and the instance that broadcast the event. See About the event object.

  • A listener object remains active until explicitly removed using EventDispatcher.removeEventListener(). For example:

    myComponent.removeEventListener("change", ListenerObj);

Using listener objects

TOP

To use a listener object, you can either use the this keyword to specify the current object as the listener, use an object that already exists in your application, or create a new object.

  • Use this in most situations.

    It's often easiest to use the current object (this) as a listener, because its scope contains the components that need to react when the event is broadcast.

  • Use an existing object if it is convenient.

    For example, in a Flash Form Application, you may want to use a form as a listener object if that form contains the components that react to the event. Place the code on a frame of the form's timeline.

  • Use a new listener object if many components are broadcasting an event (for example, the click event) and you want only certain listener objects to respond.

If you use the this object, define a function with the same name as the event you want to handle; the syntax is as follows:

function eventName(evtObj:Object){

// your code here

};

If you want to use a new listener object, you must create the object, define a property with the same name as the events, and assign the property to a callback function that executes when the event is broadcast, as follows:

var listenerObject:Object = new Object();

listenerObject.eventName = function(evtObj:Object){

// your code here

};

If you want to use an existing object, use the same syntax as a new listener object, without creating the new object, as shown here:

existingObject.eventName = function(evtObj:Object){

// your code here

};

TIP The evtObj parameter is an object that is automatically generated when an event is triggered and passed to the callback function. The event object has properties that contain information about the event. For details, see About the event object.

Finally, you call the addEventListener() method from the component instance that broadcasts the event. The addEventListener() method takes two parameters: a string indicating the name of the event and a reference to the listener object.

componentInstance.addEventListener("eventName", listenerObject);

Here is the whole code segment, which you can copy and paste. Be sure to replace any code in italics with actual values; you can use listenerObject and evtObj or any other legal identifiers, but you must change eventName to the name of the event.

var listenerObject:Object = new Object();

listenerObject.eventName = function(evtObj:Object){

// code placed here executes

// when the event is triggered

};

componentInstance.addEventListener("eventName", listenerObject);

The following code segment uses the this keyword as the listener object:

function eventName(evtObj:Object){

// code placed here executes

// when the event is triggered

}

componentInstance.addEventListener("eventName", this);

You can call addEventListener() from any component instance; it is mixed in to every component from the EventDispatcher class. (A "mix-in" is a class that provides specific features that augment the behavior of another class.) For more information, see EventDispatcher.addEventListener() in the Components Language Reference.

For information about the events a component broadcasts, see the component's entry in the Components Language Reference. For example, Button component events are listed in the Button component section (or Help > Components Language Reference > Button component > Button class > Event summary for the Button class).

To register a listener object in a Flash (FLA) file:

  1. In Flash, select File > New and create a new Flash document.

  2. Drag a Button component to the Stage from the Components panel.

  3. In the Property inspector, enter the instance name myButton.

  4. Drag a TextInput component to the Stage from the Components panel.

  5. In the Property inspector, enter the instance name myText.

  6. Select Frame 1 in the Timeline.

  7. Select Window > Actions.

  8. In the Actions panel, enter the following code:

    var myButton:mx.controls.Button;

    var myText:mx.controls.TextInput;

    function click(evt){

    myText.text = evt.target;

    }

    myButton.addEventListener("click", this);

    The target property of the event object, evt, is a reference to the instance broadcasting the event. This code displays the value of the target property in the TextInput component.

To register a listener object in a class (AS) file:

  1. Open the file TipCalculator.fla from the location specified in Working with Components.

  2. Open the file TipCalculator.as from the location specified in Working with Components.

  3. In the FLA file, select form1 and view the class name, TipCalculator, in the Property inspector.

    This is the link between the form and the class file. All the code for this application is in the TipCalculator.as file. The form assumes the properties and behaviors defined by the class assigned to it.

  4. In the AS file, scroll to line 25, public function onLoad():Void.

    The onLoad() function executes when the form loads into Flash Player. In the body of the function, the subtotal TextInput instance and the three RadioButton instances, percentRadio15, percentRadio18, and percentRadio20, call the addEventListener() method to register a listener with an event.

  5. Look at line 27, subtotal.addEventListener("change", this).

    When you call addEventListener(), you must pass it two parameters. The first is a string indicating the name of the event that is broadcast--in this case, "change". The second is a reference to either an object or a function that handles the event. In this case, the parameter is the keyword this, which refers to an instance of the class file (an object). Flash then

    looks on the object for a function with the name of the event.

  6. Look at line 63, public function change(event:Object):Void.

    This is the function that executes when the subtotal TextInput instance changes.

  7. Select TipCalculator.fla and select Control > Test Movie to test the file.

Using the handleEvent callback function

TOP

You can also use listener objects that support a handleEvent function. Regardless of the name of the event that is broadcast, the listener object's handleEvent method is called. You must use an if..else or a switch statement to handle multiple events. For example, the following code uses an if..else statement to handle the click and change events:

// define the handleEvent function

// pass it evt as the event object parameter

function handleEvent(evt){

// check if the event was a click

if (evt.type == "click"){

// do something if the event was click

} else if (evt.type == "change"){

// do something else if the event was change

}

};

// register the listener object to

// two different component instances

// because the function is defined on

// "this" object, the listener is this.

instance.addEventListener("click", this);

instance2.addEventListener("change", this);

Using listener functions

TOP

Unlike the handleEvent syntax, several listener functions can handle different events. So instead of having the if and else if checks in myHandler, you can just define myChangeHandler for the change event and myScrollHandler for the scroll event and register them, as shown here:

myList.addEventListener("change", myChangeHandler);

myList.addEventListener("scroll", myScrollHandler);

To use a listener function, you must first define a function:

function myFunction:Function(evtObj:Object){

// your code here

}

TIP The evtObj parameter is an object that is automatically generated when an event is triggered and passed to the function. The event object has properties that contain information about the event. For details, see About the event object.

Then you call the addEventListener() method from the component instance that broadcasts the event. The addEventListener() method takes two parameters: a string indicating the name of the event and a reference to the function.

componentInstance.addEventListener("eventName", myFunction);

You can call addEventListener() from any component instance; it is included in every UI component from the EventDispatcher class. For more information, see EventDispatcher.addEventListener().

For information about the events a component broadcasts, see each component's entry in the Components Language Reference.

To register a listener object in a Flash (FLA) file:

  1. In Flash, select File > New and create a new Flash document.

  2. Drag a List component to the Stage from the Components panel.

  3. In the Property inspector, enter the instance name myList.

  4. Select Frame 1 in the Timeline.

  5. Select Window > Actions.

  6. In the Actions panel, enter the following code:

    // declare variables

    var myList:mx.controls.List;

    var myHandler:Function;

    // add items to the list

    myList.addItem("Bird");

    myList.addItem("Dog");

    myList.addItem("Fish");

    myList.addItem("Cat");

    myList.addItem("Ape");

    myList.addItem("Monkey");

    // define myHandler function

    function myHandler(eventObj:Object){

    // use the eventObj parameter

    // to capture the event type

    if (eventObj.type == "change"){

    trace("The list changed");

    } else if (eventObj.type == "scroll"){

    trace("The list was scrolled");

    }

    }

    // Register the myHandler function with myList.

    // When an item is selected (triggers the change event) or the

    // list is scrolled, myHandler executes.

    myList.addEventListener("change", myHandler);

    myList.addEventListener("scroll", myHandler);

    NOTE The type property of the event object, evt, is a reference to the event name.

  7. Select Control > Test Movie; then select an item in the list and scroll the list to see the results in the Output panel.

CAUTION In a listener function, the keyword this refers to the component instance that calls addEventListener(), not to the timeline or the class where the function is defined. However, you can use the Delegate class to delegate the listener function to a different scope. See Delegating events. To see an example of function scoping, see About scope in listeners.

About scope in listeners

TOP

Scope refers to the object within which a function executes. Any variable references within that function are recognized as properties of that object. You can use the Delegate class to specify the scope of a listener. For more information, see Delegating events.

As discussed earlier, you register a listener with a component instance by calling addEventListener(). This method takes two parameters: a string indicating the name of the event, and a reference to either an object or a function. The following table lists the scope of each parameter type:

Listener type

Scope

Object

Listener object.

Function

Component instance broadcasting the event.

If you pass addEventListener() an object, the callback function assigned to that object (or the function defined on that object) is invoked in the scope of the object. This means that the keyword this, when used inside the callback function, refers to the listener object, as follows:

var lo:Object = new Object();

lo.click = function(evt){

// this refers to the object lo

trace(this);

}

myButton.addEventListener("click", lo);

However, if you pass addEventListener() a function, the function is invoked in the scope of the component instance that calls addEventListener(). This means that the keyword this, when used inside the function, refers to the broadcasting component instance. This causes a problem if you're defining the function in a class file. You cannot access the properties and methods of the class file with the expected paths because this doesn't point to an instance of the class. To work around this problem, use the Delegate class to delegate a function to the correct scope. See Delegating events.

The following code illustrates the scoping of a function when passed to addEventListener() in a class file. To use this code, copy it into an ActionScript (AS) file named Cart.as. Create a Flash (FLA) file with a Button component, myButton, and a DataGrid component, myGrid. Select both components on the Stage and press F8 to convert them into a new symbol named Cart. In the Linkage properties for the Cart symbol, assign it the class Cart.

class Cart extends MovieClip {

var myButton:mx.controls.Button;

var myGrid:mx.controls.DataGrid;

function myHandler(eventObj:Object){

// Use the eventObj parameter

// to capture the event type.

if (eventObj.type == "click"){

/* Send the value of this to the Output panel.

Because myHandler is a function that is not defined

on a listener object, this is a reference to the

component instance to which myHandler is registered

(myButton). Also, since this doesn't reference an

instance of the Cart class, myGrid is undefined.

*/

trace("this: " + this);

trace("myGrid: " + myGrid);

}

}

// register the myHandler function with myButton

// when the button is clicked, myHandler executes

function onLoad():Void{

myButton.addEventListener("click", myHandler);

}

}

Delegating events

TOP

You can import the Delegate class into your scripts or classes to delegate events to specific scopes and functions (see Delegate class in the Components Language Reference). To import the Delegate class, use the following syntax:

import mx.utils.Delegate;

compInstance.addEventListener("eventName", Delegate.create(scopeObject, function));

The scopeObject parameter specifies the scope in which the specified function parameter is called.

There are two common uses for calling Delegate.create():

  • To dispatch the same event to two different functions.

    See Delegating events to functions.

  • To call functions within the scope of the containing class.

    When you pass a function as a parameter to addEventListener(), the function is invoked in the scope of the broadcaster component instance, not the object in which it is declared. See Delegating the scope of a function.

Delegating events to functions

Calling Delegate.create() is useful if you have two components that broadcast events of the same name. For example, if you have a check box and a button, you would have to use the switch statement on the information you get from the eventObject.target property in order to determine which component is broadcasting the click event.

To use the following code, place a check box named myCheckBox_chb and a button named myButton_btn on the Stage. Select both instances and press F8 to create a new symbol. Click Advanced if the dialog box is in basic mode, and select Export for ActionScript. Enter Cart in the AS 2.0 Class text box. In the Property inspector, set the instance name for the new symbol to anything you want. The symbol is now associated with the Cart class and an instance of the symbol becomes an instance of this class.

import mx.controls.Button;

import mx.controls.CheckBox;

class Cart {

var myCheckBox_chb:CheckBox;

var myButton_btn:Button;

function onLoad() {

myCheckBox_chb.addEventListener("click", this);

myButton_btn.addEventListener("click", this);

}

function click(eventObj:Object) {

switch(eventObj.target) {

case myButton_btn:

// sends the broadcaster instance name

// and the event type to the Output panel

trace(eventObj.target + ": " + eventObj.type);

break;

case myCheckBox_chb:

trace(eventObj.target + ": " + eventObj.type);

break;

}

}

}

The following code is the same class file (Cart.as) modified to use Delegate:

import mx.utils.Delegate;

import mx.controls.Button;

import mx.controls.CheckBox;

class Cart {

var myCheckBox_chb:CheckBox;

var myButton_btn:Button;

function onLoad() {

myCheckBox_chb.addEventListener("click", Delegate.create(this, chb_onClick));

myButton_btn.addEventListener("click", Delegate.create(this, btn_onClick));

}

// two separate functions handle the events

function chb_onClick(eventObj:Object) {

// sends the broadcaster instance name

// and the event type to the Output panel

trace(eventObj.target + ": " + eventObj.type);

// sends the absolute path of the symbol

// that you associated with the Cart class

// in the FLA file to the Output panel

trace(this)

}

function btn_onClick(eventObj:Object) {

trace(eventObj.target + ": " + eventObj.type);

}

}

Delegating the scope of a function

The addEventListener() method requires two parameters: the name of an event and a reference to a listener. The listener can either be an object or a function. If you pass an object, the callback function assigned to the object is invoked in the scope of the object. However, if you pass a function, the function is invoked in the scope of the component instance that calls addEventListener(). (For more information, see About scope in listeners.)

Because the function is invoked in the scope of the broadcaster instance, the keyword this in the body of the function points to the broadcaster instance, not to the class that contains the function. Therefore, you cannot access the properties and methods of the class that contains the function. Use the Delegate class to delegate the scope of a function to the containing class so that you can access the properties and methods of the containing class.

The following example uses the same approach as the previous section (see Delegating events to functions) with a variation of the Cart.as class file:

import mx.controls.Button;

import mx.controls.CheckBox;

class Cart {

var myCheckBox_chb:CheckBox;

var myButton_btn:Button;

// define a variable to access

// from the chb_onClick function

var i:Number = 10

function onLoad() {

myCheckBox_chb.addEventListener("click", chb_onClick);

}

function chb_onClick(eventObj:Object) {

// You would expect to be able to access

// the i variable and output 10.

// However, this sends undefined

// to the Output panel because

// the function isn't scoped to

// the Cart instance where i is defined.

trace(i);

}

}

To access the properties and methods of the Cart class, call Delegate.create() as the second parameter of addEventListener(), as follows:

import mx.utils.Delegate;

import mx.controls.Button;

import mx.controls.CheckBox;

class Cart {

var myCheckBox_chb:CheckBox;

var myButton_btn:Button;

// define a variable to access

// from the chb_onClick function

var i:Number = 10

function onLoad() {

myCheckBox_chb.addEventListener("click", Delegate.create(this, chb_onClick));

}

function chb_onClick(eventObj:Object) {

// Sends 10 to the Output panel

// because the function is scoped to

// the Cart instance

trace(i);

}

}

About the event object

TOP

The event object is an instance of the ActionScript Object class; it has the following properties that contain information about an event.

Property

Description

type

A string indicating the name of the event.

target

A reference to the component instance broadcasting the event.

When an event has additional properties, they are listed in the event's entry in the Components Dictionary.

The event object is automatically generated when an event is triggered and passed to the listener object's callback function or the listener function.

You can use the event object inside the function to access the name of the event that was broadcast, or the instance name of the component that broadcast the event. From the instance name, you can access other component properties. For example, the following code uses the target property of the evtObj event object to access the label property of the myButton instance and sends the value to the Output panel:

var myButton:mx.controls.Button;

Var listener:Object;

listener = new Object();

listener.click = function(evtObj){

trace("The " + evtObj.target.label + " button was clicked");

}

myButton.addEventListener("click", listener);

Using the on() event handler

TOP

You can assign the on() event handler to a component instance, just as you would assign a handler to a button or movie clip. An on() event handler can be useful for simple testing, but for all applications, use event listeners, instead. For more information, see Using listeners to handle events.

When you use the keyword this within an on() handler attached directly to a component (assigned to the component instance in the Actions panel), this refers to the component instance. For example, the following code, attached directly to the Button component instance myButton, displays "_level0.myButton" in the Output panel:

on(click){

trace(this);

}

To use the on() event handler:

  1. Drag a User Interface component to the Stage.

    For example, drag a Button component to the Sage.

  2. On the Stage, select the component and open the Actions panel.

  3. Add the on() handler to the Actions panel in the format:

    on(event){

    //your statements go here

    }

    For example:

    on(click){

    trace(this);

    }

    Flash runs the code inside the on() handler when the event for the on() handler occurs (in this case, a button click).

    Select Control > Test Movie and click the button to see the output.

Copyright ADOBE - All Rights Reserved Worldwide

 

 

More Topics:

Working with Flash Documents

How to work in Flash WorkSpace

Working with Projects in Flash

Process to Build your First Application in Flash

Using Symbols, Instances and Library Assets in Flash

How to Build Video Player in Flash

How to Work with Color, Strokes and Fills in Flash

How to Create Document in Flash

What is Vector and Bitmap Graphics in Flash

How to Create a Banner in Flash, Part 1

How to Work with Text in Flash

How to Create a Banner in Flash, Part 2

How to Use Imported Artwork in Flash

How to Create a Banner in Flash, Part 3

How to Work with Graphic Objects in Flash

How to Work with Layers in Flash

How to Use Filters and Blends

Working with Graphics in Flash

What is Accessibility Features in Flash

How to Create Motion (Shape Tween & Motion Tween) in Flash

How to Create an Application in Flash

What is Masking in Flash

How to Work with Video in Flash

How to Use Layout Tools in Flash

What are Behaviors in Flash

How to Work with Sound in Flash

How to Create Symbols and Instances in Flash

What is ActionScript in Flash

How to Write ActionScript With Script Assist in Flash

How to Add Button Animation and Navigation in Flash

What is Data Integration in Flash

How to Work with Screens

How to Create a Presentation with Screens

What is Extending Flash

How to Create Multilanguage Text in Flash

How to Create Graphics: Draw in Flash

What is Flash Lite

Ways of Data Integration

How to Create Graphics: Create a Timeline Animation in Flash

Getting Started with Flash Lite in Flash

How to Publish Flash Documents

How to Create Graphics: Making Animations with Easing

Learning Flash Lite 1.X ActionScript in Flash

How to Export Flash Content and Images from Flash

How to Create Graphics: Applying Gradients in Flash

Process of Writing and Editing ActionScript 2.0 in Flash

How to Create Accessible Content in Flash

How to Create Graphics: Apply Graphic Filters and Blends

What is Data and Data Types in Flash

Process of Printing from SWF Files in Flash

Using ActionScript: How to Use Script Assist mode in Flash

Learn Syntax and Language Fundamentals in Flash

How to Create E-learning Content in Flash

Using ActionScript: How to Write Scripts in Flash

Working with Functions and Methods in Flash

Process of Using Templates in Flash

Using ActionScript: Process of Adding Interactivity in Flash

What are Classes in Flash

Control Tag Summary of XML to UI in Flash

Using ActionScript: How to Create a Form with Conditional Logic and Send Data in Flash

What is Inheritance in Flash

What is Data Integration: Overview

Using ActionScript: How to Work with Objects and Classes in Flash

Overview on Interfaces in Flash

What is Data Integration: Using XML for a Timesheet

How to Work with Text and Strings in Flash

How to use Handling Events in Flash

What is Data Integration: Using XUpdate to Update the Timesheet

Learning Animation, Filters and Drawings in Flash

How to Work with Movie Clips in Flash

How to Create Interaction with ActionScript in Flash

How to Work with Images, Sound, and Video in Flash

How to Work with External Data in Flash

What is Security in Flash

How to Debug Applications in Flash

List of Error Messages in Flash

Using Object-Oriented Programming with ActionScript 1.0 in Flash

How to Write Scripts for Earlier Versions of Flash Player in Flash

List of all Keyboard Keys and Key Code Values for using in Flash

Terminology

Introduction to Components in Flash

What are Components in Flash

How to Create an Application with Components

How to Work with Components in Flash

How to Handle Component Events in Flash

How to Customize Components in Flash

How to Create Components in Flash

What is Collection Properties in Flash