Passing arguments to event listeners in AS3

AS3 does not have a direct option to send arguments to event listeners. A lot of times we come across situations where it is important to pass some data to the listener.

Though not out of the box, A separate class can be created and used to achieve this functionality. This class will act as an intermediary which will store the data and in turn will deliver it to the listener.

Have a look at the sample code below

{code}
var ea:EventArguments = new EventArguments(handleClick, { arg1:”Hello”, arg2:var1 });
btn1.addEventListener(MouseEvent.CLICK, ea.call);

private function handleClick(e:Event, ob:Object) {
// ob is the argument object
}
{/code}

The EventArguments object saves in itself the argument object and a reference to the listener handleClick. The method call in EventArguments object is assigned as listener which will in turn call the final handleClick with arguments. Below is the class definition.

{code type=”javascript”}
package cb.util
{

public class EventArguments
{

private var callBack:Function;
private var arg:Object;

public function EventArguments(aCB:Function, aOB:Object) {
callBack = aCB;
arg = aOB;
}

public function call(e:*) {
callBack(e, arg);
}

}

}
{/code}

This class is created to send one object as an argument. A custom EventArguments class can be created as per requirement. It should be noted that over usage of this technique might result in memory leaks of EventArguments objects as they are not deleted. However this workaround can be used as an alternative instead of changing the application architecture.

One thought on “Passing arguments to event listeners in AS3

Leave a Reply

Your email address will not be published. Required fields are marked *