Sunday, September 5, 2010

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

Today we will learn how to save space and make your code more efficient using functions.

Let's take a simple example... We have 3 buttons, that change some text value on the screen. Like this:


Each button behaves differently, so the most simple way to do this would be something like this:

mc.addEventListener(MouseEvent.CLICK, clickManager);
function clickManager(MouseEvent):void{
 myText.text="Test one"
 }
 
mc2.addEventListener(MouseEvent.CLICK, clickManager2);
function clickManager2(MouseEvent):void{
 myText.text="Test two"
 }
 
mc3.addEventListener(MouseEvent.CLICK, clickManager3);
function clickManager3(MouseEvent):void{
 myText.text="Test three"
 }

And now imagine that we have 50 buttons like this. Not a really happy thought, is it? But, no worries! We can optimize our code in many ways.

The first way is to create one function that can handle all the buttons. The one function, to rule them all... We can pass parameters to the function to tell the button what do we want it to do.

Here:

function addButton(mc, passText){
mc.addEventListener(MouseEvent.CLICK, clickManager);
function clickManager(MouseEvent):void{
 myText.text=passText
 }
}

We have created a function that we can pass the name of a button and text to display. 'mc' is the name of our button and 'passText' is the text we want to display. We can also tweak the function a bit to make it do other things, such as go to a specific frame, etc. Anyway, let's add interractivity to our buttons:

addButton(btn1, "Test one");
addButton(btn2, "Test two");
addButton(btn3, "Test three");

Another advantage of using this method is that if we need to change something for all the buttons, we only need to change one function. It doesn't have to be limited to buttons, though.

There we go! In the next tutorial, I will write about another way of shortening your code like this.

Thanks for reading!

Related:

How to shorten your code using AS3: Way 2

No comments:

Post a Comment