【问题标题】:Timeline, event listeners, cleanup时间线、事件监听器、清理
【发布时间】:2012-05-13 01:53:28
【问题描述】:

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

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

即使我在时间轴上使用对象,我仍在编写文档类。

【问题讨论】:

  • 如果你想确保它被垃圾回收,移除事件监听器。
  • 是时候拉伸我的关键帧了。当一个项目从舞台上移除时,有没有办法让一个类移除它自己的事件监听器?

标签: events actionscript


【解决方案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));
        }
    }
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-11-25
    • 1970-01-01
    • 2020-03-06
    • 1970-01-01
    • 2023-03-14
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多