I'm working on a game where users can win buttons/badges as awards. I estimate there will be around 500 awards, in all.
I want to allow the users to sell their duplicate/unwanted badges to the bank and buy new ones from the bank.
I am showing the badges in multiple awards frames. Below the badges, I show the count, along with a "Buy" and "Sell" button.
My question is: What's the best way to handle SO MANY buy & sell buttons? Is there a way around coding 1000 eventListeners and 1000 eventHandlers?
One possible solution is to name my buttons, incrementally, like "buy_mc1", "buy_mc2", etc. Then do a loop to create listeners for this["buy_mc" + i]. However, I would then have to make VERY sure that I link these back correctly to the awards.
Currently, I have an "award_mc" field in my database, which stores the name of the movieclip in my .fla. From that, I can access related assets, like the count field, like: this[db.award_mc + "_count"].txt.
Unfortunately, this method does not lend itself well to looped access.
Maybe I can create an array of movieclip names that are in synch with the buy/sell buttons. For example:
myArray = {aMissionAward, anotherAward, ubernessAward};
My buttons would be: buy_0, buy_1, buy_2, etc.
When someone clicks a button, I can link buy_2 to "ubernessAward", then look for "ubernessAward" on the database.
How can I get the number from the button, though? Even if I can loop through setting up the eventListeners, will I have to set up individuatl eventHandlers to process the correct index number?
I'm open to suggestions on another way to do this.
-------------------------- EDIT ----------------------------
Here's my solution. Props to Jens Struwe for pointing me in the right direction.
I was not able to get this to work with buttons on the stage. Apparently, buttons are a static class. MovieClips are dynamic, so I was able to get this to work by using MovieClips. Here's what I did:
Added 3 MovieClips to the stage. Named them "mc0", "mc1", and "mc2".
Add this AS3 code:
for (var i:Number=0; i<3; i++)
{
this["mc" + i].addEventListener( MouseEvent.CLICK, onMcClick );
this["mc" + i].awardKey = i;
}
function onMcClick( evt:MouseEvent ):void
{
trace("MC ID = " +(evt.target).awardKey);
switch ((evt.target).awardKey)
{
case 0:
trace(" Do stuff for 0");
break;
case 1:
trace(" Do stuff for 1");
break;
case 2:
trace(" Do stuff for 2");
break;
}
}
From here, I can tie the awardKey to an array of MovieClip names. Then, I can use the MovieClip names to read my database.
This is why I come to Stack Overflow, FIRST, when I have a problem. :)