10.12 Copying Movie Clip Event Handlers

ActionScript for Flash MX: The Definitive Guide, 2nd Edition
By Colin Moock
Chapter 10.  Events and Event Handling

Here's a quick point that has important ramifications: onClipEvent( ) and on( ) handlers are duplicated when a movie clip is duplicated via the duplicateMovieClip( ) function. However, event handler properties, such as onEnterFrame( ), are not! Suppose, for example, we have a movie clip on stage named square, which has an onClipEvent(load) handler defined:

onClipEvent (load) {   trace("movie loaded"); }

What happens when we duplicate square to create square2?

square.duplicateMovieClip("square2", 0);

Answer: Because the onClipEvent(load) handler is copied to square2 when we duplicate square, the birth of square2 causes its load handler to execute, which displays "movie loaded" in the Output window. By using this automatic retention of handlers, we can create slick recursive functions with very powerful results. For a demonstration, refer to MovieClip.onLoad( ) in the ActionScript Language Reference.

In contrast, suppose we have a movie clip named circle and we assign it an onEnterFrame( ) event handler property as follows:

circle.onEnterFrame = function ( ) {   trace(this._name); }

What happens when we duplicate circle to create circle2?

circle.duplicateMovieClip("circle2", 1);

Answer: Only circle's name appears in the Output window. The onEnterFrame( ) event handler property is not copied to circle2, so circle2's name does not appear in the Output window. To force every duplicate of the circle clip to define an onEnterFrame( ) event handler property, we can set the property on a frame of circle's timeline:

this.onEnterFrame = function ( ) {   trace(this._name); }

Even more eloquently, we can define circle as a MovieClip subclass, and define the onEnterFrame( ) handler on the circle constructor's prototype. There's much more to come on that topic in Chapter 14.

     



    ActionScript for Flash MX. The Definitive Guide
    ActionScript for Flash MX: The Definitive Guide, Second Edition
    ISBN: 059600396X
    EAN: 2147483647
    Year: 2002
    Pages: 780
    Authors: Colin Moock

    flylib.com © 2008-2017.
    If you may any questions please contact us: flylib@qtcs.net