Home > Flex > Using recursion to perform an action on all DisplayObject children

Using recursion to perform an action on all DisplayObject children

September 18th, 2008

One of our animators recently handed me some Flash built training animations (SWF) that were to be viewed in our Flex shell. In this case we needed playback controls like pause, play, next, back and so on to work with these animations. The pause functionality in this case was problematic. Sometimes this just requires a simple stop() action but more often than not animators build animations that are comprised of many smaller MovieClip animations that are re-used quite a bit on the stage. Issuing a stop() on the root level MovieClip doesn’t stop all sub-timlines as they operate independently from the root timeline and doesn’t result in a true pause. You’ll need issue a stop on all children of the MovieClip in this case to freeze everything in its place.

You might have handled this same thing in AS2 using a for loop:

for (var m in this){
 
    if (typeof(this[mov]=="movieclip"){
        this[mov].stop();
    }
 
}

All in all this worked nicely as it could grab the full hierarchy of children. Unfortunately this no longer works in AS3. The closest thing to it would be a for loop using the number of children in a DisplayObject.

for (var i:uint = 0; i < mc.numChildren; i++){
     if (typeof(this[mov]=="movieclip"){	
         mc.getChildAt(i).stop();
     }
}

The problem with this is it only gets the direct children of the DisplayObject and none of their children’s children – and so on. However, we can fix that by wrapping it in a recursive function.

private function stopAllMovieClips(mc:*) : void {
 
	 	trace("Stop: ", mc.name);
 
		 if(mc is MovieClip) mc.stop();
 
		 for (var i:int = 0; i < mc.numChildren; i++) 
		 if (mc.getChildAt(i) is MovieClip){
                      stopMovieClip(mc.getChildAt(i));
                 }
 
}
 
stopAllMovieClips(this);

Notice that you can’t strongly type the argument for this function because you’ll come across a different class types when sifting through all children (Sprite, MovieClip, Graphic, etc). Of course MovieClip isn’t the only type of object this will work on and you aren’t limited to stop(). Any descendant of DisplayObject that has children or Flex Container is fair game here and you can perform nearly any action you want.

ian Flex

  1. No comments yet.
  1. No trackbacks yet.
You must be logged in to post a comment.