Combining functions in AS3
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;
}
}
Hello, my name is Amanda Rodriguez and I am a Web Designer and Tattoo Artist living in Astoria, NY. I graduated from RISD in 2005 with a BFA in Furniture Design. This site is meant to display my work in the several fields I have pursued thus far in my life. I am very passionate about the things that I do and I am constantly striving to be better. I am always looking for someone new to tattoo... so email me!
Post new comment