Book HomeActionScript: The Definitive GuideSearch this book

10.16. Dynamic Movie Clip Event Handlers

Early in this chapter, we learned about two kinds of events in Flash -- those that are attached to movie clips and buttons and those that are attached to other data objects such as XML and XMLSocket. To create event handlers for data objects, we assign the handler function name as a property of the object. Recall the syntax to add a function dynamically:

myXMLDoc.onLoad = function ( ) { trace("all done loading!"); };

Dynamic function assignment lets us change the behavior of the handler during movie playback. All we have to do is reassign the handler property:

myXMLDoc.onLoad = function ( ) { gotoAndPlay("displayData"); };

Or we can even disable the handler altogether:

myXMLDoc.onLoad = function ( ) { return; };

Unfortunately, handlers of movie clip and button events are not nearly so flexible; they cannot be changed or removed during movie playback. Furthermore, movie clip event handlers cannot be attached to the main movie timeline of any movie! It's impossible to directly create an event handler for a movie's _root clip.

In order to work around these limitations, we can -- in the case of the enterFrame and the user-input events -- use empty movie clips to simulate dynamic event-handler removal and alteration. Empty movie clips even let us simulate _root-level events. We've already seen the technique in Chapter 8, "Loop Statements", where we learned how to create an event loop as follows:

  1. Create an empty movie clip named process.

  2. Place another empty clip called eventClip inside process.

  3. On eventClip, attach the desired event handler. The code in the eventClip's handler should target the process clip's host timeline, like this:

    onClipEvent (mouseMove) {
      _ parent._ parent.doSomeFunction( );
    }
  4. To export process for use with the attachMovie( ) function, select it in the Library and choose Options Linkage. Set Linkage to Export This Symbol, and assign an appropriate identifier (e.g., "mouseMoveProcess").

  5. Finally, to engage the event handler, attach the process clip to the appropriate timeline using attachMovie( ).

  6. To disengage the handler, remove the process clip using removeMovieClip( ).

For step-by-step instructions on how to use this technique with the enterFrame event, see Section 8.7.2, "Flash 5 Clip Event Loops" in Chapter 8, "Loop Statements".



Library Navigation Links

Copyright © 2002 O'Reilly & Associates. All rights reserved.