3.03.2010

AS3 Tips of the Day - removeChild()

Our Tip of the Day is DisplayObjectContainer's removeChild() method:

AS3's method removeChild() is a method of DisplayObjectContainer and Inheritance by:
-> DisplayObjectContainer -> InteractiveObject -> DisplayObject -> EventDispatcher -> Object.
-> import flash.display

removeChild() method is not the same as AS2's removeMovieClip(). This are the difference of removeChild and removeMovieClip:
1. removeChild will output and error if you use removeChild in a null object. While removeMovieClip will just ignore if there is a null.

Well, to avoid this error, here are some tips to use removeChild():
1. If you need to isntantiate a movieclip by removing it to stage before adding, but this depends on the instance. I always use this method (removing child before adding child, in some instances)
package {
import flash.display.*;
import flash.events.TimerEvent;
import flash.utils.Timer;

public class Main extends MovieClip {
var arr:Array = new Array()

public function Main():void {
/// creating Timer instance t
var t:Timer = new Timer(1000, 0);

/// add event listener to Timer t, and has a callback function onTimer()
t.addEventListener(TimerEvent.TIMER, onTimer);

/// start the Timer t
t.start();
}

/// callback function onTimer for Timer t
private function onTimer(evt:TimerEvent):void {
/// if arr.length > 5 all movieclips on stage will be removed
if (arr.length > 5) {
/// this is how to removeChild in a stage, by putting a child in a Array
for (var i:int = 0; i < arr.length; i++) {
removeChild(arr[i]);
}
/// will need to instantiate the Array arr
arr = new Array();
}

/// will need to instantiate the Array arr
var mc:Sprite = new Sprite()
mc.graphics.beginFill(Math.random() * 0xffffff);
mc.graphics.drawCircle(Math.random() * 100, Math.random() * 100, Math.random() * 20);
addChild(mc);

/// push the mc in a Array.
arr.push(mc);
}
}

}

2. removeChild by 'name'
/// addChild mc with name "myMc".
var mc:Sprite = new Sprite();
mc.name = "myMc";
addChild(mc);

Iif you want to remove the child by name used:
removeChild(getChildByName("myMc"));

3. To remove directly the instance, but if you don't know if the instance is in the stage, just use try/catch methods:
try {
removeChild(mc);
} catch (err:Error){}

No comments:

Post a Comment