NOTE: Please click here for a HTML DOM version of this technique.

Sometimes it is useful to be able to iterate through our entire display list–or all of the display objects within a specific display object container–and either perform an operation on each object or access a property of each object. We need to use recursion in order to do this because child elements of a display object container may themselves be a display object container. WARNING! It can become quite processor intensive using recursion to iterate through a large number of objects. Below is an Actionscript 3 example which puts this technique into practice. All source files can be downloaded here.

First we define a class which will be responsible for iterating through the display list and calling a method on each child object. The method will be supplied as an argument and must define a display object as one of its own arguments. This allows us to define a method we would like to apply to all of our display objects externally and independent of the class.

 
package com
{
	import flash.display.*;
 
	public class DisplayObjectIterator
	{
		public function DisplayObjectIterator(){}
 
		public function iterate(task:Function,dispObjContainer:DisplayObjectContainer):void
		{
			for(var x:int;x<dispObjContainer.numChildren;x++)
			{
				var dispObj:DisplayObject = dispObjContainer.getChildAt(x);
 
				task(dispObj);
 
				if(dispObj is DisplayObjectContainer)
					this.iterate(task,dispObj as DisplayObjectContainer);
			}
		}
 
	}
}

Next we will use the class to simply trace all of our objects to the output, this method will be applied to every display object in the flash movie’s display list.

package
{
	import flash.display.*;
	import com.*;
 
	public class Main extends Sprite
	{
		public function Main()
		{
			var dispObjIterator:DisplayObjectIterator = new DisplayObjectIterator();
			dispObjIterator.iterate(traceDispObj,this);
		}
 
		private function traceDispObj(dispObj:DisplayObject):void
		{
			trace(dispObj);
		}
	}
}

We could use the iterator class for something more useful such as providing more information about each object or counting the number of certain objects at run time. ie: for memory profiling. Please click here to download the full source and an example.

The problem with recursion is it’s very easy to create an infinite loop.

The problem with recursion is it’s very easy to create an infinite loop…….