Optimizing Flash Buttons (Part 1)

In the past, whenever I needed buttons within Flash (whether movieclip or actual button instances) I would select the instance (_mc_opt01) on the stage open up the Actions panel and paste in the following code:

on(rollOver){
_root._mc_opt01.gotoAndPlay("rollover");
}
on(rollOut){
_root._mc_opt01.gotoAndPlay("rollout");
}
on(release){
getURL("mypage.php");
}

Being one who likes to modularize, I decided to try and modify my code/approach and make it more portable and easier to edit. I created a custom function and added a function call to my button instance to replace the getURL method. So it became…

on(rollOver){
_root._mc_opt01.gotoAndPlay("rollover");
}
on(rollOut){
_root._mc_opt01.gotoAndPlay("rollout");
}
on(release){
_root.getPage(1);
}

And my actual function definition would be on a frame and would look something like the following…

var path = "/index.php";
var pg_1 = path + "?id=1";
function getPage(page){
var newPage = eval("pg_" + page);
getURL(newPage);
}

This, of course, works, but it is not ideal because it uses eval(). We can replace it with this:

var newPage = _root["pg_" + page];

Then I realized I could take the code on my button instance one step further by doing the following:

on(rollOver){
var clipID = 1;
_root["_mc_opt0" + clipID].gotoAndPlay("rollover");
}
on(rollOut){
_root["_mc_opt0" + clipID].gotoAndPlay("rollout");
}
on(release){
_root.functionGetPage(clipID);
}

The advantages of using buttons this way is of course for modularity and customization, etc. Now of course this approach may not be optimal because it requires more code, but on full-Flash websites (or hybrid websites) using this method will save valuable time in searching for button/movieclip instances that need to have the URL (or whatever) modified.

For my purposes, this code reduces the likelihood of mistakes caused by manual button replication (during authoring); because there is not as much that needs to be modified before compiling and exporting the file. Anyway, I hope someone else finds this useful; it was for me.