开发者

Way to detect when a child is removed from a DisplayObjectContainer?

Is there a way to detect when a child is removed from a DisplayObjectContainer? I tried overriding removeChild(), but this doesn't appear to trigger when the child is removed by adding it to another container (via a call to addChild()开发者_StackOverflow on the new container). I'm not aware of any events that trigger, either...

I know that you can do this with higher-level Flex classes, but I'm using a Pure AS3 project.


Update:
As Roy has pointed out in the comments, because events (including Event.REMOVED) bubble up, then simply adding an event listener for the REMOVED event to the DisplayObjectContainer is sufficient; it will be called when any child objects are removed from the container (even when it's because the object was added to a different container).

The event's target property will be the child that is being removed, and the currentTarget will always be the container itself.

Note that this event will also fire if the entire container itself is removed from its container; a simple if (e.target == e.currentTarget) return; should handle that case.

Original answer below:


You can add an event listener for the Event.REMOVED event to every DisplayObject that is added to your DisplayObjectContainer. Then the object itself will tell you that it's been removed, instead of having to rely on the DisplayObjectContainer for notifications.

If this also doesn't fire when the object is moved from one container to another, then as a workaround you could also listen for the ADDED event and check if the display object is still in your container when that fires.

Don't forget to remove the event listeners once the object is removed from your container, otherwise you could end up with memory leaks, multiple calls to event listeners for the same object, etc.


As long as the child is on the stage, you can listen to Event.REMOVED_FROM_STAGE. This example traces "remove".

private function init():void {
    var parent:Sprite = new Sprite();
    var test:Sprite = new Sprite();
    test.addEventListener(Event.REMOVED_FROM_STAGE, remove);
    parent.addChild(test);
    stage.addChild(parent);
    parent.removeChild(test);
}

private function remove(e:Event):void {
    trace("remove");
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜