Monday, September 6, 2010

How to shorten your code using functions in AS3: Way 2

In this tutorial we will universalize our code using just one Listener.

In the last tutorial, we had 3 buttons with a listener for each of them. However, we can get the same results with just one listener! Here's how it works: we create one MouseEvent.CLICK listener for stage, and then check which item did user click on. Here's an example:

stage.addEventListener(MouseEvent.CLICK, allManager);

function allManager(event:MouseEvent){
 trace(event.target.name);
 }

Using the code above, we can retrieve instance names of objects we click on. So if we have many buttons and each of them has to return an unique piece of text, we can use this method.

I have decided to put all my buttons and all the text values in an Associative Array. Each element has 2 properties - mc (instance name of the object on stage) and txt (text to display upon click).

Take a look:

var btnArray = [];

stage.addEventListener(MouseEvent.CLICK, allManager);
function allManager(event:MouseEvent)
{
for (var i:int=0; i<btnArray.length; i++)
{
if (event.target == btnArray[i].mc)
{
myText.text = btnArray[i].txt;
}
}
}

Now if we want to add a button that returns "Hello", we do this:

btnArray.push({mc:btn, txt:"Hello"});

We can turn this into a function:

function addButton(bt, tx)
{
btnArray.push({mc: bt, txt: tx});
}

So the final code would be:

var btnArray = [];

stage.addEventListener(MouseEvent.CLICK, allManager);
function allManager(event:MouseEvent)
{
for (var i:int=0; i<btnArray.length; i++)
{
if (event.target == btnArray[i].mc)
{
myText.text = btnArray[i].txt;
}
}
}

function addButton(bt, tx)
{
btnArray.push({mc: bt, txt: tx});
}

Now if we have 10 buttons, we can easily add them using addButton function! And we only have one listener!! Let's see it in action (the example below only took 31 lines of code):


Thanks for reading! Hope this was helpful.

Related:

How to shorten your code using AS3: Way 1

1 comment:

Anonymous said...

Hi! Thank you! You just helped me out :) Kriszto

Post a Comment