How to Pass Parameters to an Event Listener
Anyone who has done any serious web application development has used event listeners. After dealing with the cross browser syntax differences you might want to be able to pass a parameter with a event. The traditional method for adding event listeners doesn't allow for parameters, but there is a workaround.
Suppose I have an HTML object called button. If I want to add a traditional event listener I would do something like this:
button.addEventListener(“click”, listener, false);
The parameter listener is the name of the function you want to call. If you try to pass a variable in the traditional way listener(aVar), it will execute the function instead of assigning it to the button’s click event.
The work around is to attach a JavaScript object to button.
var myListener = new ButtonHandler(element, aVar);
myListener.init();
function ButtonHandler(element, aVar) {
this.elem = element;
this.myVar = aVar;
var me = this;
this.init = function() {
this.elem.addEventListener(“click”, this.listener, false);
}
this.listener = function() {
alert(me.myVar);
}
}
It’s pretty intimidating at first, but let’s look through it. The first two lines create and initialize a ButtonHandler object. In the ButtonHandler, I assign each variable to the object. I also create a variable me, that points to the object. Otherwise when the function is executed it will refer to the document and not the button. The init function assigns the event listener to itself. When the event is triggered it calls an internal function call listener. The listener refers to itself and grabs the variable we passed in earlier.
It’s a lot of work, but it works. Something similar should work in ActionScript too.