We have talked already about scope issues and addressing. They're
tricky. Well there's very particular issue I want to talk to you about: the use
of _root.
Using the _root
of the movie can be very practical for small applications, because it is a very
simple and fast way to scope your variables, and there is very little chance
that it will change during the movie. The
_root will always
be the _root.
Fine.
The problem is: there are situations when the _root does change. Especially when
you load movies into target with
loadMovie.
Imagine you load the .swf my_movie.swf into the clip
_root.container.
Imagine that you have references to the
_root in
my_movie.swf. Everything will work fine if you play that movie by itself, but
when you load it, the movie will react just as if it was a movie clip. So when
you wrote _root,
Flash will look in the
_root of the main movie, and not the
_root of the
loaded movie, in our case
_root.container.
That's why scoping a variable from the
_root is not
recommended: this limits the portability of the code.
Don't worry, there's still hope. You actually have 2 ways out of it.
Basically, you'll have to use the keyword
_parent as many
times as needed to go back to the
_root. It's not
very elegant but it works. The problem is that you may have to change a lot of
code, especially if the structure of the movie changes, and it's not always easy
to find the right path.
You create a variable to reference the main timeline instead of using
_root. This
allows for easy modification of a single parameter if the timeline structure
changes. All you have to do is add this line of code to the main timeline of the
loaded movie:
- _global.myAppMain
= this;
When you've done that, you can refer to the
_root of the
loaded movie from anywhere in that movie with
myAppMain, even
when you load that movie into target. For instance, to set the variable
count located in
the _root of the
loaded movie, you'll simply have to do:
- myAppMain.count
= 3;