(This is part 1 of a series of posts on ways to pass arguments to a function through event listeners. For part two, see here, for part three, , and for part four, .)
One of the things I often wonder about actionscript 3 is the best way to pass arguments to a function through an event listener. Typically when you add an event listener, you simply specify a type of event, and the name of the function to call when the event is dispatched. (You may also specify the optional parameters useCapture, priority, and useWeakReference, but seeing as how that’s not relevant to the subject at hand, we’ll be focusing on just the first two):
myButton.addEventListener(MouseEvent.CLICK, outputText);
When ‘myButton’ was clicked, this would then call the function ‘outputText’, which would take just one parameter – the event that triggered it:
function outputText(evt:MouseEvent):void { trace("Hello World!"); }
But what if you wanted to have multiple buttons that all triggered one function, each passing a different parameter? This functionality isn’t supported as standard, so a little improvising is required. This series of posts aims to discuss all your options, from custom events (the good), to external variables (the bad), and anonymous functions (the ugly).
The Goal
We are going to try to create event listeners which call the following function, and each pass in a different string:
function outputText(evt:MouseEvent, str:String):void { trace(str); }
Method 1 – Anonymous Function
The first workaround is the anonymous function. You should really only use this if you fully understand what you’re doing, and if that’s the case you probably know a better way of doing it in the first place. If you’re unsure of what you’re doing, littering your code with anonymous functions is a surefire path to a memory leak.
Essentially, the anonymous function is just a function which you are writing rather than calling inside the event listener.
myButton.addEventListener(MouseEvent.CLICK, myFunction(evt:MouseEvent){ outputText(evt, "Button 1 Pressed!") });
This looks a bit daunting – and that’s another problem with it, it just obfuscates the code and makes it harder to maintain. What’s happening is the event is only really triggering the function ‘myFunction’, which is in turn calling our ‘outputText’ function and passing it a string. By adding this listener to multiple buttons and changing the string being passed, ‘outputText’ will trace a different string for each button. Note that ‘myFunction’ is first passing the event itself, making it and all it’s methods available to ‘outputText’.
So that’s how to use anonymous functions to pass arguments through a listener. Next time I’ll be looking at using variables to store parameters.
