Recipe 7.10 Discovering Nested Movie Clips
7.10.1 Problem
You want to use ActionScript to
retrieve
an array of movie clip instances nested within a specific movie clip.
7.10.2 Solution
Use a for . . . in statement
to loop through all the contents of
the movie clip, and if the content is an instance of the
MovieClip class (as indicated by the
instanceof operator), add it to an array of the
nested movie clips.
7.10.3 Discussion
Movie clips can be nested within other movie clips. A nested clip
instance is stored as a property of its parent clip. Since movie clip
instances are objects, you can access all the nested movie clips
using a for . . . in statement. However, a basic
for . . . in statement lists other properties in
addition to nested movie clips. This example displays not only movie
clips nested in _root, but also any timeline
variables, functions, and the built-in $version
variable:
for (var item in _root) {
trace(item + ": " + _root[item]);
}
To separate nested movie clips from the rest of a
clip's contents, you can use the
instanceof operator to check if an item is an
instance of the MovieClip class, as follows:
// The if statement disregards everything but movie clips.
for (var item in _root) {
if (_root[item] instanceof MovieClip) {
trace(item + ": " + _root[item]);
}
}
You can also write a simple custom method for the
MovieClip class that returns an array of nested
movie clips:
MovieClip.prototype.getMovieClips = function ( ) {
// Define the array to contain the movie clip references.
var mcs = new Array( );
// Loop through all the contents of the movie clip.
for (var i in this) {
// Add any nested movie clips to the array.
if (this[i] instanceof MovieClip) {
mcs.push(this[i]);
}
}
return mcs;
};
Here is an example that uses the getMovieClips(
) method to display all the movie clips within
_root:
trace(_root.getMovieClips( ));
Here is a version that recursively displays all movie clips in a tree:
MovieClip.prototype.showMovieClips = function ( ) {
// Loop through all the contents of the movie clip.
for (var i in this) {
// Add any nested movie clips to the array.
if (this[i] instanceof MovieClip) {
trace (this[i]);
// Recursively call this function to show any nested clips
this[i].showMovieClips( );
}
}
};
// Example usage:
_root.showMovieClips( );
7.10.4 See Also
Recipe 6.13
|