Combining functions in AS3

May 5 2009

Combining functions in AS3

Posted by amandar

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;
}
}

Post new comment
  • Web page addresses and e-mail addresses turn into links automatically.
  • Allowed HTML tags: <a> <em> <strong> <cite> <code> <ul> <ol> <li> <dl> <dt> <dd>
  • Lines and paragraphs break automatically.
  • You may post code using <code>...</code> (generic) or <?php ... ?> (highlighted PHP) tags.

More information about formatting options