Passing Arguments Through a Listener Part 1 – Anonymous Function

January 18th, 2010

(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). Read the rest of this entry »