12.10. Listening for Events

Problem

You want to perform an action in response to an event, such as when the Stage is resized, a text field’s contents are scrolled, the mouse button is clicked, or a key is pressed.

Solution

Create a listener object that defines an appropriate listener event handler and add it as a listener using addListener( ).

Discussion

ActionScript’s listener events allow one or more objects to respond to events that occur for other objects. A listener object (an object that has been added as a listener) is notified when one of the supported listener events occurs. For example, the built-in Key, Mouse, Selection, and Stage objects generate one or more listener events, as do instances of the TextField class, as shown in Table 12-1.

Table 12-1. Listener events for built-in objects and instances

Object

Built-in listener events

Key object

onKeyDown

onKeyUp

Mouse object

onMouseDown

onMouseMove

onMouseUp

Selection object

onSetFocus

Stage object

onResize

TextField instance

onChanged

onScroller

A listener object can be any kind of object, such as a text field, movie clip, or custom object. The listener object must define a listener event handler to respond to the event of interest, and it must be added as a listener using addListener( ). For example, to respond to text-scrolling events, you can create an object that defines an onScroller( ) method and then register the object to the text field of interest using the addListener( ) method. ...

Get Actionscript Cookbook now with O’Reilly online learning.

O’Reilly members experience live online training, plus books, videos, and digital content from 200+ publishers.