(This is part 3 of a series of posts on ways to pass arguments to a function through event listeners. For part one, see here, for part two, see here, and for part four, see here.)
For today’s method of passing values to a function through a listener, we’re going to bend the rules a little. The result will be a set of slightly different listeners, but each will eventually call our desired function. At the expense of bending the rules, we’re going to end up with what is probably the best solution short of creating custom events, albeit quite a long-winded one.
Method 3 – Interim Functions
Essentially, what we’re going to end up with is a separate function for each listener to call. This may seem to go against everything we’re trying to achieve, but the key is that each of these functions will only serve to call the function that we really want, ”outputText’. This is really overkill for us, considering that the function that we’re calling in the end is only one line – why not just put the trace statement from outputText into each interim function instead and be done with it? This is certainly true in our case, but consider what would happen if the function you were trying to call had instead 20 lines. Say you had 5 buttons, each one with different arguments to pass – now you have 100 lines of code, where if you were using interim functions, you’d have a single 20 line function and 5 interim functions with 1 line each. Easier to read, and much easier to maintain.
So, here’s the example. We’re going to be setting up two different buttons to give a solid idea of what’s going on:
myButton1.addEventListener(MouseEvent.CLICK, btn1Clicked); myButton2.addEventListener(MouseEvent.CLICK, btn2Clicked);
Now we need to write our interim functions – the functions that will be called by those event listeners, and will in turn call outputText:
function btn1Clicked(evt:MouseEvent):void { outputText("Button 1 was clicked!"); } function btn2Clicked(evt:MouseEvent):void { outputText("Button 2 was clicked!"); }
Because we are now calling the function ourselves (it is not being called directly by a listener), we need to modify the outputText function so that it is not expecting an event as an argument – just a string:
function outputText(str:String):void { trace(str); }
And now we have our desired result. Clicking a button will correctly trace which button was clicked to the output panel. Like I said at the start of this post, this is probably the best, most robust solution to the problem of passing arguments through listeners if you don’t want to get your hands dirty creating custom events. If, however, you feel like you’re ready to take the next step, come back next time when we’ll be taking a closer look at just how to do that.
