How to delete all event listeners at once in AS3

天涯浪子 提交于 2020-02-01 04:58:40

问题


I'm making a small game in as3.

The game contains 10 levels.

When i enter 1 level everything is alright. But when i enter the second level (frame) the event listeners from the first frame are still working and a recieve a warning saying ' Cannot access an object of null objct reference'. This is because i delete every object of the first level and th add the objects from stage 2.

I've tried using removeEventListeners, but it doesn't work, cause ENTER_FRAME Listeners work one more time after I remove the Event Listeners.

I've tried using different frames for different levels, bit it doesn't work. Also i tried using 1 frmae for all 10 frames, but i recieve much many warning and the Flash Loader is overloaded.

How can i switch through levels (back and forward)? Thanks in advance.

  addEventListener(Event.ENTER_FRAME, subtracting2);
     arrListeners.pop(); // poping it out of the array because it will be deleted after the count reaches 0
     function subtracting2 (e:Event):void
     {
        count--;
        var FAcoef:Number = count/30; //
        FadeAway.alpha = FAcoef; //                   Some effect like FadeAway
        setChildIndex(FadeAway, numChildren - 1); //
        if(count == 0)
       {
            setChildIndex(FadeAway, 0);
            removeEventListener(Event.ENTER_FRAME, subtracting2);
        }
    }

回答1:


There is no built-in way to remove all listeners.

You could use weak references to let the listeners be removed when the object is Garbage Collected.

object.addEventListener( ......, ......., false, 0, true );

Or you could add the removeAllListeners functionality yourself, here is some info:
http://blog.reyco1.com/method-of-removing-all-event-listeners/ (Have a look at Ion comment)

But.. you shouldn't need any of the above if you take care to remove every event listener straight away when it is not needed any more.

If you have a class with one or more event listeners which are needed till the end of the instance's life, you should create a destroy() function. In that destroy() function you would remove all the event listeners.

In your case, you could call destroy() before you go to second level(frame).



来源:https://stackoverflow.com/questions/12144812/how-to-delete-all-event-listeners-at-once-in-as3

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!