Handling Events

 <  Day Day Up  >  

Any event triggered in an application, regardless of whether it comes from a user or the system, can be handled. Events are handled in one of two ways, either with listeners or with callbacks.

Handling Messages with Listeners

Listeners are a basic means for handling events in object-oriented languages. A listener is an object that is notified when an event occurs. To create a listener, the object on which an event will occur (such as an instance of the WebServices class) needs to be notified about which object will respond to its events. This is known as adding a listener to an object.

Listeners use a publisher-subscriber methodology, in that object A can subscribe to listen to object B. When object B broadcasts any messages, object A, as a listener, will be able to react to them. For a listener to react , it must have a method with the same name as the message being broadcast. Consider the example in Figure 7.1.

Figure 7.1. The various departments of a consulting organization are set as listeners to the sales department; they are waiting for a message that a client project has been sold.


In this example, four people are set to listen to a single person. The billing, development, legal, and networking people are listening to the salesperson. They are waiting for an indication that a sale has been closed. When the salesperson broadcasts that he or she has closed a sale, each of the four listening persons has a series of tasks that needs to be done. Legal will create the contracts, networking will prepare the servers, and so on.

As it turns out, the salesperson has lots of different messages that may be broadcast, but these four listeners are interested in only one particular message, gotJob . For them to respond to only that message, each needs to have a gotJob () method, which can fire when the salesperson broadcasts the gotJob event. Any messages that are broadcast to a listener, but to which the listener does not need to have a response, will be ignored as long as the listener does not have a method matching the name of the broadcast message. In the example from Figure 7.1, the four listeners will respond to the gotJob event because they each have a gotJob() method, but they will have no response to any other message broadcast by sales, so other communications, such as callingProspect , will be ignored by these listeners.

This same paradigm applies to objects. One object can be set to listen to another. Many built-in classes are designed with methods that enable other objects to listen to them. Any class with the methods addListener() and removeListener() are specifically built to enable external objects to listen for their events. Many of the native classes, such as Key , Mouse , and TextField , also have these methods.

To instruct one object to listen to an object that is broadcasting events, the broadcasting object's addListener() method is invoked. The addListener() method takes the listening objects as an argument. Listing 7.1 shows an example of an object listening to the Key class to capture any keys pressed by the user.

Listing 7.1. An Object Is Assigned to Listen to the Key Class so That Any Key Pressed by a User Can Be Detected
 var myListenerObject:Object = new Object(); myListenerObject.onKeyDown = function(){       trace("The ASCII code for the key you pressed is: " + Key.getAscii()); } Key.addListener(myListenerObject); 

Listing 7.1 begins by creating myListenerObject as a new instance of the Object class. Next, a method named onKeyDown is added to myListenerObject. This method has the same name as the event that is broadcast by the Key class each time a user presses a key. This method is defined to trace a message, showing the ASCII code for the key that was pressed. Lastly, myListenerObject is assigned as a listener to the Key class.


As was mentioned in Chapter 4, certain classes, such as Key and Mouse , are known as singleton or top-level classes. These classes do not need to be instantiated ; a single instance of them already exists. These singleton classes have their methods, including addListener and remoteListener , set as static methods, so they can be invoked directly against the class, as opposed to against instances of the class.

Although these classes have specific methods for adding and removing listeners, the "Using AsBroadcaster to Broadcast Custom Messages" section of this chapter will explore how any class or object in ActionScript can broadcast messages.

In addition to the ability of an object to listen to another object for messages, many internal objects are built to listen for specific events. For example, the MovieClip class is built to automatically listen for any of the events listed for it. This enables a MovieClip instance to react to its own events instead of relying on an external object to react to them.

An object handling its own events is fairly common in the object-oriented world. Often when a user interacts with an item on the Stage, the item is expected to have a reaction. For example, a MovieClip object might be built to change colors when the user puts the mouse over it. This type of interaction would not involve an external object acting as a listener, but would instead have the MovieClip instance listening for its own onMouseOver event.

Often, an object needs to respond to an event only under certain circumstances. Should an object no longer need to respond to events from another object, the removeListener() method can be invoked. After an object has been removed as a listener, it will no longer respond to any broadcast events.

We can keep an object listening to another object, but remove its ability to react to a particular event. By simply removing the method matching a particular event, an object will still be able to listen to the other events from the broadcasting object, but it will no longer respond to the event matching the deleted method, as shown in the following code:

 this.onRelease = function(){       this.changeColor(0xff0000);       this.onRelease = null; } 

In the preceding code, an object is built to handle a user clicking and releasing it. When the object is clicked, its changeColor() method is invoked and the onRelease method is deleted. This happens because the method set the onRelease event handler equal to null . After the onRelease method has been set to null , it will no longer have a response to a user's click and release.

Handling Messages with Callbacks

The other way messages can be handled in ActionScript 2.0 code is through the use of callbacks. Callbacks exist to handle asynchronous method calls. They are frequently used when loading external data, as will be seen in Chapters 11 “15. When a call is made from the Flash Player to a server, some amount of time will pass before the server responds to the call. This encompasses the time taken for the message to travel across the network from the Player to the server, for the server to receive the message and send a response, and for that response to travel across the network and be received again by the Player. Examine Figure 7.2.

Figure 7.2. Asynchronous calls are handled with callbacks.


This process might take only a fraction of a second to occur, or it may take several minutes. For this reason, calls of this sort are handled asynchronously. This means that the Flash Player does not stop running the movie and wait for the data to arrive. Instead, it continues running and has the ability to react to the results, regardless of when they arrive .

The reaction to the result is handled by a callback , which is a special type of method automatically invoked when certain asynchronous operations, such as the Flash Player receiving data from the server, occur.

There are fundamental differences between listeners and callbacks:

  • One message might have several listeners; a message is limited to a single callback.

  • Listeners receive the message as soon as it is sent; callbacks are asynchronous and do not receive the message until the data is returned to it.

Listing 7.2 shows an example of a callback in action.

Listing 7.2. Using a Callback Method with the LoadVars Object
 var myLoadVars:LoadVars = new LoadVars(); myLoadVars.onLoad = function(){       // call back only called when data loaded       title.text = this.title;       trace("Time when data is received: " + getTimer()+" ms"); } myLoadVars.load("listing7_2.txt"); trace("Time when method was called: " +getTimer() +" ms"); 


The nature of the LoadVars object is explained in depth in Chapter 12, "XML and Flash."

Listing 7.2 begins by creating myLoadVars as an instance of the LoadVars class. Next, the callback method onLoad() is defined, which, when invoked, will populate a text field named title with the title property loaded from the server. This method also fires a trace statement that will illustrate the time discrepancy between when the data is requested from the server and when it is received. Next, the load() method is invoked, requesting that the contents of a file named listing8_2.txt be read into the myLoadVars object. Last, a trace statement is used to output the amount of time that has elapsed at the point when the load() method is called.

It is important to note that the onLoad callback is never explicitly invoked (the code myLoadVars.onLoad() never explicitly appears). This method is invoked automatically as a callback, executing when the requested file has been loaded. Figure 7.3 shows the results when the code in Listing 7.2 is run. As can be seen, the dynamic text field title is populated with the title from the text file.

Figure 7.3. The callback method onLoad is invoked when the file is completely loaded, which is 100 milliseconds after the request is sent.


Callbacks are not needed every time an object passes a message to another; however, in the case of asynchronous operations, they are invaluable.

 <  Day Day Up  >  

Object-Oriented Programming with ActionScript 2.0
Object-Oriented Programming with ActionScript 2.0
ISBN: 0735713804
EAN: 2147483647
Year: 2004
Pages: 162

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