Interesting feature of the contains() method
Posted: 10/10/08
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
Popular categories:
Recent posts:
- Mac OS find files using regex
- ADB device driver won't install
- Eclipse: An error has occurred. See the log file .metadata/.log
- Updated blinkbox iPad app
- Nexus 7 doesn't appear in adb devices list
- Improve the keyboard in the Samsung ICS update
- 403 Forbidden error on Mac web server
- Getting error with manually created NIB?
- Adding/removing items from PATH on Mac
- Presenting at Flash Oxford
- more...
Publications:
Places you'll find me:
Archive:
- February 2024
- January 2024
- December 2023
- November 2023
- October 2023
- September 2023
- August 2023
- July 2023
- June 2023
- May 2023
- April 2023
- March 2023