Combining functions in AS3 back

May 05, 2009
0 Comments

A friend of mine recently shared this technique with me, and I thought it was so cool I decided to post it up here.

If you have a lot of buttons in a project and they all have roll over, roll out and click states, your action script is going to be cluttered with functions. For example, this is how I was initially taught to have a single button with an on off and click state:

button_mc.buttonMode = true;
button_mc.mouseChildren = false;
button_mc.addEventListener(MouseEvent.ROLL_OVER, btnOver);
button_mc.addEventListener(MouseEvent.ROLL_OUT, btnOut);
button_mc.addEventListener(MouseEvent.CLICK, btnClick);

function btnOver(e:Event){
e.target.gotoAndStop(2);
}
function btnOut(e:Event){
e.target.gotoAndStop(1);
}
function btnOver(e:Event){
navigateToURL(new URLRequest("http://www.google.com"), "_self");
}

Now this doesn't look like too much code but when you start to have multiple buttons it can get really cluttered.. so here is the same thing but in one function:

button_mc.buttonMode = true;
button_mc.mouseChildren = false;
button_mc.addEventListener(MouseEvent.ROLL_OVER, btnFunc);
button_mc.addEventListener(MouseEvent.ROLL_OUT, btnFunc);
button_mc.addEventListener(MouseEvent.CLICK, btnFunc);

function btnFunc(e:MouseEvent){
switch(e.type){
case "rollOver":
e.target.gotoAndStop(2);
break;
case "rollOut":
e.target.gotoAndStop(1);
break;
case "click":
navigateToURL(new URLRequest("http://www.google.com"), "_self");
break;
default:
break;
}
}