Additional event syntax

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 buttonInstance:

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

Note: In a function listener, the this keyword is buttonInstance, not the Timeline on which the function is defined.

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);

There is one additional event syntax style, which should only be used when you are authoring a component and know that a particular object is the only listener for an event. In such a situation, you can take advantage of the fact that the v2 event model always calls a method on the component instance that is the event name plus "Handler". For example, if you want to handle the click event, you would write the following code:

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

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

For more information, see Creating Components.