AS2 Version of MovieClip.getChildByName()?
-
06-07-2019 - |
Question
I'm trying to be responsible with my "DOM" references in this little Flash 8/AS2 project.
What has become increasingly frustrating is obtaining references to other movie clips and objects. For example, currently my code to access the submit button of a form looks something like this
var b:Button = _level0.instance4.submitBtn;
I was hoping there was an instance-retrieval method for AS2 similar to AS3's MovieClip.getChildByName()
or even Javascript's document.getElementById()
. Because hard-coding the names of these anonymous instances (like instance4
in the above) just feel really, really dirty.
But, I can't find anything of the sort at this AS2 Reference.
Solution
If the MovieClip was placed on the stage in the Flash IDE, you can give it a proper instance name in the properties panel.
If it was dynamically added, you can also give it a name, and additionally store a reference:
var my_MC=createEmptyMovieClip("instanceName", depth);
In either case, you can then adress them with _parentClip.instanceName
or my_MC.
OTHER TIPS
There are a couple ways you can do this. The easiest way is to use Array notation. Your previous example, which looks like this:
var b:Button = _root.instance4.submitBtn;
would look like this in Array notation:
var b:Button = _root["instance4"].submitBtn;
So if you wanted to loop through 100 buttons already created and set the alpha to 0:
for( var i:Number = 0; i < 101; i++)
{
var button:Button = _root["instance"+i].submitBtn;
button._alpha = 0;
}
You can also use eval("instance4") to do the same thing, but I'm a little foggy on the scoping issues involved.
You could just write it yourself (code not tested but you get the idea):
MovieClip.prototype.getElementByName = function(name : String) : Object
{
var s : String;
var mc : Movieclip = null;
for( s in this )
{
if( this[s] instanceof MovieClip )
{
if( s == name )
{
mc = this[ s ];
break;
}
mc = this[s].getElementByName( name );
}
}
return( mc );
}