Using component event listeners

The most powerful way to handle component events is to use listeners. Events are broadcast by components and any object that is registered to the event broadcaster (component instance) as a listener can be notified of the event. The listener is assigned a function that handles the event. You can register multiple listeners to one component instance. You can also register one listener to multiple component instances.

To use the event listener model, you create a listener object with a property that is the name of the event. The property is assigned to a callback function. Then you call the UIEventDispatcher.addEventListener() method on the component instance that's broadcasting the event and pass it the name of the event and the name of the listener object. Calling the UIEventDispatcher.addEventListener() method is called "registering" or "subscribing" a listener, as in the following:

listenerObject.eventName = function(evtObj){
  // your code here
};
componentInstance.addEventListener("eventName", listenerObject);

In the above code, the keyword this, if used in the callback function, is scoped to the listenerObject.

The evtObj parameter is an event object that is automatically generated when an event is triggered and passed to the listener object callback function. The event object has properties that contain information about the event. For more information, see UIEventDispatcher class.

For information about the events a component broadcasts, see each component's entry in Components Dictionary.

To register an event listener, do the following:

  1. Drag a Button component to the Stage from the Components panel.
  2. In the Property inspector, enter the instance name button.
  3. Drag a TextInput component to the Stage from the Components panel.
  4. In the Property inspector, enter the instance name myText.
  5. Select Frame 1 in the Timeline.
  6. Select Window > Actions.
  7. In the Actions panel, enter the following code:
    form = new Object();
    form.click = function(evt){
      myText.text = evt.target;
    }
    button.addEventListener("click", form);
    

    The target property of the event object is a reference to the instance broadcasting the event. This code displays the value of the target property in the text input field.