Hello all,
I’m aware that this topic has been covered before, but after several hours googling and experimenting, I’m not getting any closer and could really do with some help.
I’m migrating to from AS2 to AS3 and trying to get my head around best practices using listeners on buttons.
Let’s say I have ten buttons which I’ve created on my stage in the Flash IDE (these are instances of SimpleButton) which are labelled :
myBtn1
myBtn2
myBtn3
…
myBtn10
What I want to do is make a function that is called when each one is clicked on which has a parameter passed depending on which one was clicked.
In AS2, I used to achieve this by using Joey Lott’s Proxy.as class as follows:
for ( var i=1; i<=10; i++ ) {
this["myBtn"+i].onRelease = Proxy.create (this, doStuff, i);
};
private function doStuff (i:Number) : void
{
trace("Hey look! Button number "+i+" just got pressed!");
}
Now, obviously in AS3 I guess should be using Listeners instead, so I’m doing something like this:
for ( var i=1; i<=10; i++ ) {
this["myBtn"+i].addEventListener( MouseEvent.MOUSE_UP, doStuff );
};
private function doStuff (e:MouseEvent) : void
{
trace("Hey look! A button got pressed!");
trace("I know I can find it's instance name by using "+e.currentTarget);
trace("But that doesn't really help me.");
}
Using the above, I know I could stick a switch statement inside my doStuff function and use e.currentTarget to get the instance name of the button that was pressed and work out what to do that way, but that would be an awfully long-winded way of doing it.
From all the googling I’ve been doing on the subject, it seems I should be creating a custom Listener, but despite finding a few relevant board posts:
http://www.actionscript.org/forums/archive/index.php3/t-104284.html
http://board.flashkit.com/board/showthread.php?t=737627&highlight=parameter+event+listener
http://www.actionscript.org/forums/showthread.php3?t=151969&highlight=passing+parameters+listeners
…I can’t seem to get them working for the life of me, and I’m totally stuck as to what approach I should really be taking.
Another approach would be to make all my buttons movieclips instead of SimpleButtons and then to add the parameters like this:
for ( var i=1; i<=10; i++ ) {
this["myBtn"+i].myFunkyParameter = i;
this["myBtn"+i].addEventListener( MouseEvent.MOUSE_UP, doStuff );
};
private function doStuff (e:MouseEvent) : void
{
trace("Hey look! A button got pressed!");
trace("And the parameter is: "+e.currentTarget.myFunkyParameter);
}
… but it seems that you can’t add variables to SimpleButtons and I’m loathe to stop using Button-type symbols as I do find them very handy for doing quick rollovers, specifying hitAreas etc.
So can anyone help me?
Thanks!