Using on and onClipEvent with event handler methods

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. See Event handler scope.

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. For information on specifying events for on() and onClipEvent(), see Specifying events for on or onClipEvent methods.

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. For more information, see About ActionScript and events and Attaching code to objects.