Identifying event handlers

You define the event handler object or event handler function that listens for your component's events in your application's ActionScript.

The following example creates a listener object, handles a click event, and adds it as an event listener to myButton:

listener = new Object();
listener.click = function(evtObj){
  trace("The " + evtObj.target.label + " button was clicked");
}
myButton.addEventListener("click", listener);

In addition to using a listener object, you can use a function as a listener. A listener is a function if it does not belong to an object. For example, the following code creates the listener function myHandler() and registers it to myButton:

function myHandler(eventObj){
  if (eventObj.type == "click"){
    // your code here
  }
}
myButton.addEventListener("click", myHandler);

For more information on using the addEventListener() method, see Using component event listeners.

When you know that a particular object is the only listener for an event, you can take advantage of the fact that the new event model always calls a method on the component instance. This method is the event name plus the word Handler. For example, to handle the click event, write the following code:

myComponentInstance.clickHandler = function(o){
  // insert your code here
}

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

You can also use listener objects that support a handleEvent() method. Regardless of the name of the event, the listener object's handleEvent() method is called. You must use an if...else or a switch statement to handle multiple events, which makes this syntax clumsy. For example, the following code uses an if...else statement to handle the click and enter events:

myObj.handleEvent = function(o){
  if (o.type == "click"){
    // your code here
  } else if (o.type == "enter"){
    // your code here
  }
}
target.addEventListener("click", myObj);
target2.addEventListener("enter", myObj);