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 use Handling Events in Flash

Using event handler methods

Using event listeners

Using event listeners with components

Using button and movie clip event handlers

Using on and onClipEvent with event handler methods

Specifying events for on or onClipEvent methods

Attaching or assigning multiple handlers to one object

Broadcasting events from component instances

Creating movie clips with button states

Event handler scope

Scope of the this keyword

Using the Delegate class

Using event handler methods

TOP

An event handler method is a method of a class that is invoked when an event occurs on an instance of that class. For example, the MovieClip class defines an onPress event handler that is invoked whenever the mouse is pressed on a movie clip object. Unlike other methods of a class, however, you don't invoke an event handler directly; Flash Player invokes it automatically when the appropriate event occurs.

The following ActionScript classes are examples of classes that define event handlers: Button, ContextMenu, ContextMenuItem, Key, LoadVars, LocalConnection, Mouse, MovieClip, MovieClipLoader, Selection, SharedObject, Sound, Stage, TextField, XML and XMLSocket. For more information about the event handlers they provide, see the entries for each class in ActionScript 2.0 Language Reference. The word handler is added in the title of each event handler.

By default, event handler methods are undefined: when a particular event occurs, its corresponding event handler is invoked, but your application doesn't respond further to the event. To have your application respond to the event, you define a function with the function statement and then assign that function to the appropriate event handler. The function you assign to the event handler is then automatically invoked whenever the event occurs.

An event handler consists of three parts: the object to which the event applies, the name of the object's event handler method, and the function you assign to the event handler. The following example shows the basic structure of an event handler:

object.eventMethod = function () {

// Your code here, responding to event.

}

For example, suppose you have a button named next_btn on the Stage. The following code assigns a function to the button's onPress event handler; this function advances the playhead to the next frame in the current timeline:

next_btn.onPress = function () {

nextFrame();

}

Assigning a function reference In the previous code, the nextFrame() function is assigned to an event handler for onPress. You can also assign a function reference (name) to an event handler method and later define the function, as shown in the following example:

// Assign a function reference to button's onPress event handler.

next_btn.onPress = goNextFrame;

// Define goNextFrame() function.

function goNextFrame() {

nextFrame();

}

Notice in the following example that you assign the function reference, not the function's return value, to the onPress event handler:

// Incorrect!

next_btn.onPress = goNextFrame();

// Correct.

next_btn.onPress = goNextFrame;

Receiving passed parameters Some event handlers receive passed parameters that provide information about the event that occurred. For example, the TextField.onSetFocus event handler is invoked when a text field instance gains keyboard focus. This event handler receives a reference to the text field object that previously had keyboard focus.

For example, the following code inserts some text into a text field that no longer has keyboard focus:

this.createTextField("my_txt", 99, 10, 10, 200, 20);

my_txt.border = true;

my_txt.type = "input";

this.createTextField("myOther_txt", 100, 10, 50, 200, 20);

myOther_txt.border = true;

myOther_txt.type = "input";

myOther_txt.onSetFocus = function(my_txt:TextField) {

my_txt.text = "I just lost keyboard focus";

};

Event handlers for runtime objects You can also assign functions to event handlers for objects you create at runtime. For example, the following code creates a new movie clip instance (newclip_mc) and then assigns a function to the clip's onPress event handler:

this.attachMovie("symbolID", "newclip_mc", 10);

newclip_mc.onPress = function () {

trace("You pressed me");

}

Overriding event handler methods By creating a class that extends an ActionScript class, you can override event handler methods with the functions that you write. You can define an event handler in a new subclass that you can then reuse for various objects by linking any symbol in the library of the extended class to the new subclass. The following code overrides the MovieClip class's onPress event handler with a function that decreases the transparency of the movie clip:

// FadeAlpha class -- sets transparency when you click the movie clip.

class FadeAlpha extends MovieClip {

function onPress() {

this._alpha -= 10;

}

}

 

Using event listeners

TOP

Event listeners let an object, called a listener object, receive events broadcast by another object, called a broadcaster object. The broadcaster object registers the listener object to receive events generated by the broadcaster. For example, you can register a movie clip object to receive onResize notifications from the Stage, or a button instance could receive onChanged notifications from a text field object. You can register multiple listener objects to receive events from a single broadcaster, and you can register a single listener object to receive events from multiple broadcasters.

The listener-broadcaster model for events, unlike event handler methods, lets you have multiple pieces of code listen to the same event without conflict. Event models that do not use the listener/broadcaster model, such as XML.onLoad(), can be problematic when various pieces of code are listening to the same event; the different pieces of code have conflicts over control of that single XML.onLoad callback function reference. With the listener/broadcaster model, you can easily add listeners to the same event without worrying about code bottlenecks.

The following ActionScript classes can broadcast events: Key, Mouse, MovieClipLoader, Selection, Stage, and TextField. To see which listeners are available for a class, see each class entry in the ActionScript 2.0 Language Reference.

Event listener model

The event model for event listeners is similar to the model for event handlers (see Using event handler methods), with two main differences:

You assign the event handler to the listener object, not the object that broadcasts the event.

You call a special method of the broadcaster object, addListener(), which registers the listener object to receive its events.

The following code outlines the event listener model:

var listenerObject:Object = new Object();

listenerObject.eventName = function(eventObj:Object) {

// Your code here

};

broadcasterObject.addListener(listenerObject);

The code starts with an object, listenerObject, with a property eventName. Your listener object can be any object, such as an existing object, movie clip, or button instance on the Stage, or it can be an instance of any ActionScript class. For example, a custom movie clip could implement the listener methods for Stage listeners. You could even have one object that listens to several types of listeners.

The eventName property is an event that occurs on broadcasterObject, which then broadcasts the event to listenerObject. You can register multiple listeners to one event broadcaster.
You assign a function to the event listener that responds to the event in some way.

Last, you call the addListener() method on the broadcaster object, passing the listener object to the addListener() method.

To unregister a listener object from receiving events, you call the removeEventListener() method of the broadcaster object, passing it the name of the event to remove, and the listener object.

broadcasterObject.removeListener(listenerObject);

Event listener example

The following example shows how to use the onSetFocus event listener in the Selection class to create a simple focus manager for a group of input text fields. In this case, the border of the text field that receives keyboard focus is enabled (appears), and the border of the text field that does not have focus is disabled.

To create a simple focus manager with event listeners:

  1. Using the Text tool, create a text field on the Stage.

  2. Select the text field, and then in the Property inspector, select Input from the Text Type pop-up menu and select the Show Border Around Text option.

  3. Create another input text field below the first one.

    Make sure the Show Border Around Text option is not selected for this text field. You can continue to create input text fields.

  4. Select Frame 1 in the Timeline and open the Actions panel (Window > Actions).

  5. To create an object that listens for focus notification from the Selection class, enter the following code in the Actions panel:

    // Creates listener object, focusListener.

    var focusListener:Object = new Object();

    // Defines function for listener object.

    focusListener.onSetFocus = function(oldFocus_txt:TextField, newFocus_txt:TextField) {

    oldFocus_txt.border = false;

    newFocus_txt.border = true;

    }

    This code creates an object named focusListener that defines an onSetFocus property and assigns a function to the property. The function takes two parameters: a reference to the text field that does not have focus and one to the text field that has focus. The function sets the border property of the text field that does not have focus to false, and sets the border property of the text field that has focus to true.

  6. To register the focusListener object to receive events from the Selection object, add the following code to the Actions panel:

    // Registers focusListener with broadcaster.

    Selection.addListener(focusListener);

  7. Test the application (Control > Test Movie), click in the first text field, and press the Tab key to switch focus between fields.

     

Using event listeners with components

TOP

When you work with components, you have a slightly different event-listener syntax. Components generate events, and you must specifically listen for these events by using either a listener object or a custom function.

The following example shows how you can use event listeners to monitor the download progress of a dynamically loaded image.

To listen for Loader component events:

  1. Drag an instance of the Loader component onto the Stage from the Components panel.

  2. Select the loader, and type my_ldr in the Instance Name text box in the Property inspector.

  3. Add the following code to Frame 1 of the main Timeline;

    System.security.allowDomain("http://www.helpexamples.com");

    var loaderListener:Object = new Object();

    loaderListener.progress = function(evt_obj:Object):Void {

    trace(evt_obj.type); // progress

    trace("\t" + evt_obj.target.bytesLoaded + " of " + evt_obj.target.bytesTotal + " bytes loaded");

    }

    loaderListener.complete = function(evt_obj:Object):Void {

    trace(evt_obj.type); // complete

    }

    my_ldr.addEventListener("progress", loaderListener);

    my_ldr.addEventListener("complete", loaderListener);

    my_ldr.load("http://www.helpexamples.com/flash/images/image1.jpg");

    This ActionScript code defines a listener object named loaderListener, which listens for two events: progress and complete. When each of these events are dispatched, their code is executed, and debugging text is displayed in the Output panel if you test the SWF file in the authoring tool.

    Next you tell the my_ldr instance to listen for each of the two specified events (progress and complete) and specify the listener object or function to execute when the event is dispatched. Finally, the Loader.load() method is called, which triggers the image to begin downloading.

  4. Select Control > Test Movie to test the SWF file.

    The image downloads into the Loader instance on the Stage, and then several messages are displayed in the Output panel. Depending on the size of the image you download, and if the image was cached on the user's local system, the progress event might be dispatched numerous times, whereas the complete event is only dispatched after the image is completely  downloaded.

    When you work with components and dispatch events, the syntax is slightly different from the event listeners in previous examples. Most notably, you must use the addEventListener() method instead of calling addListener(). Secondly, you must specify the specific event you want to listen for as well as the event listener object or function.

Instead of using a listener object, as in the first procedure under Using event listeners with components, you can use a custom function. The code in the previous example could be rewritten as follows:

System.security.allowDomain("http://www.helpexamples.com");

my_ldr.addEventListener("progress", progressListener);

my_ldr.addEventListener("complete", completeListener);

my_ldr.load("http://www.helpexamples.com/flash/images/image1.png");

function progressListener(evt_obj:Object):Void {

trace(evt_obj.type); // progress

trace("\t" + evt_obj.target.bytesLoaded + " of " + evt_obj.target.bytesTotal + " bytes loaded");

}

function completeListener(evt_obj:Object):Void {

trace(evt_obj.type); // complete

}

NOTE : In the previous examples, the event listeners are always added before the Loader.load() method is called. If you call the Loader.load() method before you specify the event listeners, the load might complete before the event listeners are fully defined. This means that the content might display and the complete event might not be caught.

 

Using button and movie clip event handlers

TOP

You can attach event handlers directly to a button or movie clip instance on the Stage by using the onClipEvent() and on() event handlers. The onClipEvent() event handler broadcasts movie clip events, and the on() event handler handles button events.

To attach an event handler to a button or movie clip instance, click the button or movie clip instance on the Stage to bring it in focus, and then enter code in the Actions panel. The title of the Actions panel reflects that code will be attached to the button or movie clip: Actions Panel - Button or Actions Panel - Movie Clip. For guidelines about using code that's attached to button or movie clip instances, see Attaching code to objects.

NOTE : Do not confuse button and movie clip event handlers with component events, such as SimpleButton.click, UIObject.hide, and UIObject.reveal, which must be attached to component instances and are discussed in Using Components.

You can attach onClipEvent() and on() only to movie clip instances that have been placed on the Stage during authoring. You cannot attach onClipEvent() or on() to movie clip instances that are created at runtime (using the attachMovie() method, for example). To attach event handlers to objects created at runtime, use event handler methods or event listeners. (See Using event handler methods and Using event listeners.)

NOTE : Attaching onClipEvent() and on() handlers is not a recommended practice. Instead, you should put your code in frame scripts or in a class file, as demonstrated throughout this manual. For more information, see Using event handler methods and Attaching code to objects.

 

Using on and onClipEvent with event handler methods

TOP

You can, in some cases, use different techniques to handle events without conflict. Using the on() and onClipEvent() methods doesn't conflict with using event handler methods that you define.

For example, suppose you have a button in a SWF file; the button can have an on(press) handler that tells the SWF file to play, and the same button can have an onPress() method, for which you define a function that tells an object on the Stage to rotate. When you click the button, the SWF file plays and the object rotates. Depending on when and what kinds of events you want to invoke, you can use the on() and onClipEvent() methods, event handler methods, or both techniques of event handling.

However, the scope of variables and objects in on() and onClipEvent() handlers is different than in event handler and event listeners.

You can also use on() with movie clips to create movie clips that receive button events. For more information, see Creating movie clips with button states.

To use an on handler and onPress event handler:

  1. Create a new Flash document and save it as handlers.fla.

  2. Select the Rectangle Tool and draw a large square on the Stage.

  3. Select the Selection Tool, double-click the square on the Stage, and press F8 to launch the Convert to Symbol dialog box.

  4. Enter a symbol name for the box, set the type to Movie clip and click OK.

  5. Give the movie clip on the Stage an instance name of box_mc.

  6. Add the following ActionScript directly on the movie clip symbol on the Stage:

    on (press) {

    trace("on (press) {...}");

    }

  7. Add the following ActionScript to Frame 1 of the main Timeline:

    box_mc.onPress = function() {

    trace("box_mc.onPress = function() {...};");

    };

  8. Select Control > Test Movie to test the Flash document.

    When you click the movie clip symbol on the Stage, the following output is sent to the Output panel:

    on (press) {...}

    box_mc.onPress = function() {...};

    NOTE : Attaching onClipEvent() and on() handlers is not a recommended practice. Instead, you should put your code in frame scripts or in a class file, as demonstrated throughout this manual.

 

Specifying events for on or onClipEvent methods

TOP

To use an on() or onClipEvent() handler, attach it directly to an instance of a button or movie clip on the Stage and specify the event you want to handle for that instance. For a complete list of events supported by the on() and onClipEvent() event handlers.

For example, the following on() event handler executes whenever the user clicks the button to which the handler is attached:

on (press) {

trace("Thanks for pressing me.");

}

You can specify two or more events for each on() handler, separated by commas. The ActionScript in a handler executes when either of the events specified by the handler occurs. For example, the following on() handler attached to a button executes whenever the mouse rolls over and then off the button:

on (rollOver, rollOut) {

trace("You rolled over, or rolled out");

}

You can also add key press events using on() handlers. For example, the following code traces a string when you press the number 3 on the keyboard. Select a button or movie clip instance, and add the following code to the Actions panel:

on (keyPress "3") {

trace("You pressed 3")

}

Or, if you want to trace when the Enter key is pressed by a user, you could use the following code format. Select a button or movie clip instance, and add the following code to the Actions panel:

on (keyPress "<Enter>") {

trace("Enter Pressed");

}

Select Control > Test Movie, and press the Enter key to see the string trace to the Output panel. If nothing traces, select Control > Disable Keyboard Shortcuts and try again. For more information on adding keypress interactivity to your applications.

NOTE : Attaching onClipEvent() and on() handlers is not a recommended practice. Instead, you should put your code in frame scripts or in a class file, as demonstrated throughout this manual.

 

Attaching or assigning multiple handlers to one object

TOP

You can also attach more than one handler to an object if you want different scripts to run when different events occur. For example, you could attach the following onClipEvent() handlers to the same movie clip instance. The first executes when the movie clip first loads (or appears on the Stage); the second executes when the movie clip is unloaded from the Stage.

on (press) {

this.unloadMovie()

}

onClipEvent (load) {

trace("I've loaded");

}

onClipEvent (unload) {

trace("I've unloaded");

}

NOTE : Attaching onClipEvent() and on() handlers is not a recommended practice. Instead, you should put your code in frame scripts or in a class file, as demonstrated throughout this manual.

To attach multiple handlers to one object using code that's placed on the timeline, see the following example. The code attaches the onPress and onRelease handlers to a movie clip instance.

To assign multiple handlers to an object:

  1. Create a new Flash document, and name it assignMulti.fla.

  2. Select Frame 1 of the Timeline, and add the following code in the Actions panel:

    this.createEmptyMovieClip("img_mc", 10);

    var mclListener:Object = new Object();

    mclListener.onLoadInit = function(target_mc:MovieClip) {

    target_mc.onPress = function() {

    target_mc.startDrag();

    };

    target_mc.onRelease = function() {

    target_mc.stopDrag();

    };

    }

    mclListener.onLoadError = function(target_mc:MovieClip) {

    trace("error downloading image");

    }

    var img_mcl:MovieClipLoader = new MovieClipLoader();

    img_mcl.addListener(mclListener);

    img_mcl.loadClip("http://www.helpexamples.com/flash/images/image1.jpg", img_mc);

  3. Select Control > Test Movie to test the document.

    The image loads into the img_mc instance, and the onPress() and onRelease() event handlers let you drag the image around the Stage.

     

Broadcasting events from component instances

TOP

For any component instance, you can specify how an event is handled. Component events are handled differently than events broadcast from native ActionScript objects.

 

Creating movie clips with button states

TOP

When you attach an on() handler to a movie clip, or assign a function to one of the MovieClip mouse event handlers for a movie clip instance, the movie clip responds to mouse events in the same way as a button. You can also create automatic button states (Up, Over, and Down) in a movie clip by adding the frame labels _up, _over, and _down to the movie clip's timeline.
When the user moves the mouse over the movie clip or clicks it, the playhead is sent to the frame with the appropriate frame label.

To create button states in a movie clip:

  1. Create a new Flash document and save it as mcbutton.fla.

  2. Using the Rectangle Tool, draw a small rectangle (approximately 100 pixels wide by 20 pixels high) on the Stage.

  3. Double-click the shape with the Selection tool and press F8 to launch the Convert to Symbol dialog box.

  4. Enter a symbol name of mcbutton, set the symbol type to movie clip, and click OK.

  5. Double-click the movie clip symbol on the Stage to enter symbol-editing mode.

  6. Create a new layer in the movie clip's timeline and rename the new layer labels.

  7. Enter a frame label of _up in the Property inspector.

  8. Create a new layer above the default layer and labels layer.

  9. Rename the new layer actions and add the following ActionScript to Frame 1 of the movie clip's timeline:

    stop();

  10. Select Frame 10, all three layers, and select Insert > Timeline > Keyframe.

  11. Add a stop() action on Frame 10 of the actions layer, and add a frame label of _over in frame 10 of the labels layer.

  12. Select the rectangle on Frame 10 and use the Property inspector to select a different fill color.

  13. Create new keyframes on frame 20 of each of the three layers, and add a frame label of _down in the Property inspector.

  14. Modify the color of the rectangle in Frame 20 so each of the three button states have a different color.

  15. Return to the main timeline.

  16. To make the movie clip respond to mouse events, do one of the following:

    • Attach an on() event handler to the movie clip instance.

    • Assign a function to one of the movie clip object's mouse event handlers (onPress, onRelease, and so forth).

  17. Select Control > Test Movie to test the Flash document.

    Move your mouse pointer over the movie clip instance on the Stage and the movie clip automatically goes to the movie clip's _over state. Click the movie clip instance and the playhead automatically goes to the movie clip's _down state.

     

Event handler scope

TOP

The scope, or context, of variables and commands that you declare and execute within an event handler depends on the type of event handler you use: event handlers or event listeners, or on() and onClipEvent() handlers. If you're defining an event handler in a new ActionScript class, the scope also depends on how you define the event handler. This section contains both ActionScript 1.0 and ActionScript 2.0 examples.

ActionScript 1.0 examples Functions assigned to event handler methods and event listeners (as with all ActionScript functions that you write) define a local variable scope, but on() and onClipEvent() handlers do not.

For example, consider the following two event handlers. The first is an onPress event handler associated with a movie clip named clip_mc. The second is an on() handler attached to the same movie clip instance.

// Attached to clip_mc's parent clip timeline:

clip_mc.onPress = function () {

var shoeColor; // local function variable

shoeColor = "blue";

}

// on() handler attached to clip_mc:

on (press) {

var shoeColor; // no local variable scope

shoeColor = "blue";

}

Although both event handlers contain the same code, they have different results. In the first case, the color variable is local to the function defined for onPress. In the second case, because the on() handler doesn't define a local variable scope, the variable is defined in the scope of the timeline of the clip_mc movie clip.

For on() event handlers attached to buttons, rather than to movie clips, variables (as well as function and method calls) are invoked in the scope of the timeline that contains the button instance.

For instance, the following on() event handler produces different results that depend on whether it's attached to a button or movie clip object. In the first case, the play() function call starts the playhead of the timeline that contains the button; in the second case, the play() function call starts the timeline of the movie clip to which the handler is attached.

// Attached to button.

on (press) {

play(); // Plays parent timeline.

}

// Attached to movie clip.

on (press) {

play(); // Plays movie clip's timeline.

}

When attached to a button object, the play() function applies to the timeline that contains the button--that is, the button's parent timeline. But when the on(press) handler is attached to a movie clip object, the play() function call applies to the movie clip that bears the handler. If you attach the following code to a movie clip, it plays the parent timeline:

// Attached to movie clip.

on (press) {

_parent.play(); // Plays parent timeline.

}

Within an event handler or event listener definition, the same play() function applies to the timeline that contains the function definition. For example, suppose you declare the following my_mc.onPress event handler method on the timeline that contains the my_mc movie clip instance:

// Function defined on a timeline

my_mc.onPress = function () {

play(); // plays timeline that it is defined on.

};

To play the movie clip that defines the onPress event handler, refer explicitly to that clip using the this keyword, as follows:

// Function defined on root timeline

my_mc.onPress = function () {

this.play(); // plays timeline of my_mc clip.

};

However, the same code placed on the root timeline for a button instance would instead play the root timeline:

my_btn.onPress = function () {

this.play(); // plays root timeline

};

ActionScript 2.0 example The following TextLoader class is used to load a text file and display some text after it successfully loads the file.

// TextLoader.as

class TextLoader {

private var params_lv:LoadVars;

public function TextLoader() {

params_lv = new LoadVars();

params_lv.onLoad = onLoadVarsDone;

params_lv.load("http://www.helpexamples.com/flash/params.txt");

}

private function onLoadVarsDone(success:Boolean):Void {

_level0.createTextField("my_txt", 999, 0, 0, 100, 20);

_level0.my_txt.autoSize = "left";

_level0.my_txt.text = params_lv.monthNames; // undefined

}

}

This code cannot work correctly because there is a problem involving scope with the event handlers, and what this refers to is confused between the onLoad event handler and the class. The behavior that you might expect in this example is that the onLoadVarsDone() method will be invoked in the scope of the TextLoader object; but it is invoked in the scope of the LoadVars object because the method was extracted from the TextLoader object and grafted onto the LoadVars object. The LoadVars object then invokes the this.onLoad event handler when the text file is successfully loaded, and the onLoadVarsDone() function is invoked with this set to LoadVars, not TextLoader. The params_lv object resides in the this scope when it is invoked, even though the onLoadVarsDone() function relies on the params_lv object by reference. Therefore, the onLoadVarsDone() function is expecting a params_lv.params_lv instance that does not exist.

To correctly invoke the onLoadVarsDone() method in the scope of the TextLoader object, you can use the following strategy: use a function literal to create an anonymous function that calls the desired function. The owner object is still visible in the scope of the anonymous function, so it can be used to find the calling TextLoader object.

// TextLoader.as

class TextLoader {

private var params_lv:LoadVars;

public function TextLoader() {

params_lv = new LoadVars();

var owner:TextLoader = this;

params_lv.onLoad = function (success:Boolean):Void {

owner.onLoadVarsDone(success);

}

params_lv.load("http://www.helpexamples.com/flash/params.txt");

}

private function onLoadVarsDone(success:Boolean):Void {

_level0.createTextField("my_txt", 999, 0, 0, 100, 20);

_level0.my_txt.autoSize = "left";

_level0.my_txt.text = params_lv.monthNames; // January,February,March,...

}

}

 

Scope of the this keyword

TOP

The this keyword refers to the object in the currently executing scope. Depending on what type of event handler technique you use, this can refer to different objects.

Within an event handler or event listener function, this refers to the object that defines the event handler or event listener method. For example, in the following code, this refers to my_mc:

// onPress() event handler attached to main timeline:

my_mc.onPress = function () {

trace(this); // _level0.my_mc

}

Within an on() handler attached to a movie clip, this refers to the movie clip to which the on() handler is attached, as shown in the following code:

// Attached to movie clip named my_mc on main timeline

on (press) {

trace(this); // _level0.my_mc

}

Within an on() handler attached to a button, this refers to the timeline that contains the button, as shown in the following code:

// Attached to button on main timeline

on (press) {

trace(this); // _level0

}

 

Using the Delegate class

TOP

The Delegate class lets you run a function in a specific scope. This class is provided so that you can dispatch the same event to two different functions, and so that you can call functions within the scope of the containing class.

When you pass a function as a parameter to EventDispatcher.addEventListener(), the function is invoked in the scope of the broadcaster component instance, not the object in which it is declared. You can use Delegate.create() to call the function within the scope of the declaring object.

The following example shows three methods of listening for events for a Button component instance. Each way that you add event listeners to a Button component instance results in the event being dispatched in a different scope.

To use the Delegate class to listen for events:

  1. Create a new Flash document and save it as delegate.fla.

  2. Drag a Button component from the User Interface folder of the Components panel to the library.

    You add and position the button instance on the Stage using ActionScript in a later step.

  3. Add the following ActionScript to Frame 1 of the main Timeline:

    import mx.controls.Button;

    import mx.utils.Delegate;

    function clickHandler(eventObj:Object):Void {

    trace("[" + eventObj.type + "] event on " + eventObj.target + " instance.");

    trace("\t this -> " + this);

    }

    var buttonListener:Object = new Object();

    buttonListener.click = function(eventObj:Object):Void {

    trace("[" + eventObj.type + "] event on " + eventObj.target + " instance.");

    trace("\t this -> " + this);

    };

    this.createClassObject(Button, "one_button", 10, {label:"One"});

    one_button.move(10, 10);

    one_button.addEventListener("click", clickHandler);

    this.createClassObject(Button, "two_button", 20, {label:"Two"});

    two_button.move(120, 10);

    two_button.addEventListener("click", buttonListener);

    this.createClassObject(Button, "three_button", 30, {label:"Three"});

    three_button.move(230, 10);

    three_button.addEventListener("click", Delegate.create(this, clickHandler));

    The preceding code is separated into six sections (each section is separated by a blank line). The first section imports the Button class (for the Button component) as well as the Delegate class. The second section of code defines a function that you call when the user clicks some of the buttons. The third section of code creates an object that you use as an event listener, and the object listens for a single event, click.

    The remaining three sections of code each create a new Button component instance on the Stage, reposition the instance, and add an event listener for the click event. The first button adds an event listener for the click event and passes a reference to a click handler function directly. The second button adds an event listener for the click event and passes a reference to a listener object, which contains a handler for the click event. Finally, the third function adds an event listener for the click event, uses the Delegate class to dispatch the click event in the this scope (where this equals _level0) and passes a reference to the click handler function.

  4. Select Control > Test Movie to test the Flash document.

  5. Click each button instance on the Stage to see which scope in which the event is handled.

  1. Click the first button on the Stage to trace the following text in the Output panel:

[click] event on _level0.one_button instance.

this -> _level0.one_button

When you click one_button instance, the this scope refers to the button instance itself.

  1. Click the second button on the Stage to trace the following text in the Output panel:

[click] event on _level0.two_button instance.

this -> [object Object]

When you click the two_button instance, the this scope refers to the buttonListener object.

  1. Click the third button on the Stage to trace the following text in the Output panel:

[click] event on _level0.three_button instance.

this -> _level0

When you click the three_button instance, the this scope refers to the scope that you specify in the Delegate.create() method call, or in this case, _level0.

 

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