Using Listeners


You use listeners frequently in this lesson when you are using components in the interfaces. Listeners are used frequently in Flash, and are objects that do something based on who is broadcasting an event. Listeners are very similar to event handlers because they both wait for events to happen in a SWF file and then perform an action when the event occurs. There are two important distinctions between events and listeners: Listeners are caught by listener objects. Listener objects are objects with instructions that execute when a broadcaster object sends an event to the listener. Which brings you to the other difference and that is you must associate a broadcasting object (like a button) and a listener object using ActionScript. Essentially, you are telling your broadcaster to let your listener know when something happens. The listner then executes instructions from there. When you use components, you use the addEventListener method to do that and specify the event to broadcast and the listener object that will handle that event. You can see an example of listeners in the following code:

var listenerObject:Object = new Object(); listenerObject.click = function(evt) {   trace("you clicked the button."); }; myButtonComponentInstance_btn.addEventListener("click", listenerObject);

The first thing that happens here is you create an object to receive the events. Then you define a function handling the event and optionally assign it to the evt object as an argument. Flash uses the name of the event that the function catches as a property of the function. By doing this, you can have a single object catch several different events.

The last thing you do is add the event listener to a button on the Stage with an instance name of myButtonComponentInstance_btn. Then you tell the SWF file which event you are listening for (in this case, click, which triggers when the user presses and releases the button) and then pass the listenerObject as a parameter.




Macromedia Flash 8. Training from the Source
Macromedia Flash 8: Training from the Source
ISBN: 0321336291
EAN: 2147483647
Year: 2004
Pages: 230
Authors: James English

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