Aliasing root
By now, you should be familiar with our use of the root construct as a way to communicate among objects in ActionScript.
Using the conversion function MovieClip(root), we can acquire data stored in a sibling object (that is, an object that is, like the present one, also a child of the main movie), and in fact we can even change properties of siblings, and activate their methods. We can also use this technique to change the text within Text Fields defined in the main movie, and quite a few other things not yet detailed.
However, you may find it tedious to keep having to type the expression Movieclip(root) as a preamble to some property or method, especially if you need to make a long series of such references. Consider this example:
function checkOut():void
{
MovieClip(root).checkerField.visible = true;
MovieClip(root).checkerField.text = MovieClip(root).doofus.crucialVar;
}
Here we have to type MovieClip(root) three times. We can save a little of that typing by adding a line to this method:
function checkOut():void
{
var theRoot:MovieClip = MovieClip(root);
theRoot.checkerField.visible = true;
theRoot.checkerField.text = theRoot.doofus.crucialVar;
}
The trick is very simple, in fact: we just create a variable of type MovieClip, then assign the result of the conversion to that variable, instead of performing it three times over. This change also saves some computing cycles, though you'll never notice.
Since theRoot is a custom, local variable, you can use any name you like, even a shorter, one-letter designation (say, R).
One important warning, though: if you're going to use this technique, ONLY DO SO WITHIN CUSTOM METHODS. If you try to be clever, and declare your root alias with other general variables at the top of your class definition, you may encounter problems under certain circumstances. Variables declared outside of function bodies, or in some cases in the Constructor, can pick up a null value for MovieClip(root), because the statement may be executed before the class has been added to the Display List.
If you don't understand the previous sentence, don't worry. If you try to alias the root and see errors referring to a null value, put your alias assignment inside some method, preferably one other than the Constructor. Everything should work fine.
|
|