时间轴,事件监听器,清理

时间:2012-05-03 14:15:52

标签: events actionscript

如果我在前几帧的时间轴上有一个按钮,那么我将其删除......

如果已从舞台上删除按钮,我是否必须担心删除按钮的事件侦听器(MovieClip)?

我正在写一个文档类,即使我在时间轴上使用了对象。

1 个答案:

答案 0 :(得分:1)

您可以使用removedFromStage事件清除按钮实例上的所有事件侦听器:

package 
{
    import flash.display.MovieClip;
    import flash.events.Event;
    import flash.events.MouseEvent;

    public class Button extends MovieClip
    {
        public function Button():void
        {
            addListeners();
        }

        private function addListeners():void
        {
            this.addEventListener(Event.ADDED_TO_STAGE, addedHandler);
            this.addEventListener(Event.REMOVED_FROM_STAGE, removedHandler);
            this.addEventListener(MouseEvent.CLICK, clickHandler);
        }

        private function addedHandler(event:Event):void
        {
            trace("button added");
        }

        private function removedHandler(event:Event):void
        {
            trace("button removed");
            removeListeners();
        }

        private function clickHandler(event:MouseEvent):void
        {
            trace("button clicked");
        }

        private function removeListeners():void
        {
            this.removeEventListener(Event.ADDED_TO_STAGE, addedHandler);
            this.removeEventListener(Event.REMOVED_FROM_STAGE, removedHandler);
            this.removeEventListener(MouseEvent.CLICK, clickHandler);

            trace("has added listener: " + this.hasEventListener(Event.ADDED_TO_STAGE)); 
            trace("has removed listener: " + this.hasEventListener(Event.REMOVED_FROM_STAGE));
            trace("has click listener: " + this.hasEventListener(MouseEvent.CLICK));
        }
    }
}