< Day Day Up > |
Handling Events from Flash User Interface (UI) ComponentsThe components in Flash MX 2004 have their own broadcasting mechanism. Each Flash component has a method called addEventListener() , which behaves similarly to the addListener() method discussed earlier. Listing 7.3 shows a listener being added for an event of a combo box. Listing 7.3. Using addEventListener to Respond to Events from Componentsvar myResponder:Object = new Object(); var myCombo:mx.controls.ComboBox; myResponder.change = function(){ trace(myCombo.value); } myCombo.addEventListener("change",myResponder); In Listing 7.3, the addEventListener() method of a combo box is used to broadcast any change events from the combo box to the myResponder object. This example shows how similar addEventListener() is to addListener() . However, as can be seen, there is one key difference between the two methods ” addEventListener takes the name of the event as an argument in addition to the object name . This enables a single component to have different objects listening for individual events. addEventListener() also has a few other ways it can be used. Rather than specifying an object as the event listener, the second argument passed to it can instead be a function located on the main timeline, as seen in Listing 7.4: Listing 7.4. addEventListener Can Specify a Function to Respond to Events from Componentsvar myCombo:mx.controls.ComboBox; function showValue(){ trace(myCombo.value); } myCombo.addEventListener("change",showValue); Of course, in OOP, it is a best practice to avoid functions on the main timeline. Instead, you should create functions as methods on an object. Fortunately, addEventListener() also supports this construct, enabling a listener object to have any of its methods respond to an event instead of requiring the method to have the same name as the event. Although the usefulness of this might not be obvious, it can enable a single method to handle disparate events from multiple components. Listing 7.5 shows addEventListener() being used to route the change event of a combo box to a method named someMethod() within the myResponder object: Listing 7.5. addEventListener is Flexible Enough to Enable Methods of Any Name to Respond to Any Component Eventvar myResponder:Object = new Object(); var myCombo:mx.controls.ComboBox; myResponder.someMethod = function(){ trace(myCombo.value); } myCombo.addEventListener("change",myResponder.someMethod);
|
< Day Day Up > |