O'Reilly logo

Actionscript Cookbook by Joey Lott

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

12.11. Adding Listeners to Custom Classes

Problem

You want your objects of a custom class to generate listener events and support listener objects.

Solution

Write an addListener( ) method for your custom class. Use the watch( ) method to watch a property. When the property is modified, call all listeners.

Discussion

Listeners are a convenient way to automatically trigger methods on one or more objects when a property is modified within the object being listened to. Listeners are available for some classes of objects such as Key, Mouse, and TextField (see Table 12-1). Although ActionScript does not provide listeners for all objects, you can use the watch( ) method to generate listener events in response to property changes.

The watch( ) method requires at least two parameters: a string value that is the name of the property to watch and a reference to a callback function to call when the property is changed. (A callback function is simply a function that is called in response to a particular trigger.) The callback function is always automatically passed at least three values: the property name, the old value, and the new value. If the callback function returns true, the new value is assigned to the property, and if it returns false, the old value is assigned to the property. The watch( ) method can also be used for other purposes, such as implementing logic in the callback function to determine which value (old or new) should be assigned to the property. For the purposes of creating ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required