Interesting feature of the contains() method

Posted: 10/10/08

An image of Interesting feature of the contains() method

We've all been playing around with ActionScript 3.0 for some time now, but it's amazing how much of the core display list features remain a mystery to many. Now I don't intend this as a moan; actually, I want to emphasise how vast the framework is, and how even some of the most 'comprehensive' texts fail to scratch an inch below the surface.

I recently saw some code that was doing the following:

if( contains( myMC ) )

{

removeChild( myMC );

}

Now you may think "Nothing wrong with that, the guy is obviously aware of the possible run-time errors that occur when attempting to remove a child display object that isn't in the display list."

Now look at how myMC was added to the display list:

var myContainer:Sprite = new Sprite();

addChild( myContainer );

var myMC:MovieClip = new MovieClip();

myContainer.addChild( myMC );

The developer believed that the first conditional statement wouldn't return true, because the contains( DisplayObject ) method was being called on this rather than the object that was holding myMC. The actual outcome in this context is that so long as myMC is in the display list, the IF statement will always return true.

Why? Simply because contains( DisplayObject ) isn't restricted to a DisplayObjectContainer's immediate children. The contains() method will recursively look for a matching reference in all children of the DisplayObjectContainer on which the method is invoked, their children, grand-children, and so on. If anywhere in the display list hierarchy underneath a match is found, contains( DisplayObject ) will return true.

Examples of DisplayObjectContainers are Loader, Sprite, Stage

Why would the above code be a problem? In this situation, the developer only wanted to check whether myMC was a direct child of myContainer. The code, however, was always attempting to remove the child object from the wrong scope.

DisplayObjectContainer.contains() on LiveDocs

Keywords for this post: flash, player, adobe, actionscript 3, contains, DisplayObject, DisplayObjectContainer, addChild