How to remove all event listeners from a display object?

萝らか妹 提交于 2019-12-03 07:19:51

jeceuyper is right ...

a side not though: DisplayObject extends EventDispatcher, which already does implement IEventDispatcher ... so to be more precise: you need to override addEventListener and removeEventListener to keep track of the listeners ...

a few technical details: i suggest you use Dictionary to store the handler functions ... a bit slower for insertion, but much faster for removal ... also, Dictionary supports weak references, which is quite important in the case of event handling ... also keep in mind, that useCapture allows to add the same handler twice ...

good luck then ... ;)

back2dos has mentioned the approach you should use, what i did was extend the movieclip class and implemented all kinds of functions that i use on daily basis but are not part of the movieclip class. including the override for the addEventListener class

protected var listeners : Dictionary    = new Dictionary();
override public function addEventListener( type : String, listener : Function, useCapture : Boolean = false, priority : int = 0, useWeakReference : Boolean = true) : void
{
        var key : Object = {type:type,useCapture:useCapture};
        if( listeners[ key ] ) {
                removeEventListener( type, listeners[ key ], useCapture );
                listeners[ key ] = null;
        }
        listeners[ key ] = listener;

        super.addEventListener( type, listener, useCapture, priority, useWeakReference );
}
protected function removeListeners () : void
{
        try
        {
            for (var key:Object in listeners) {
                    removeEventListener( key.type, listeners[ key ], key.useCapture );
                        listeners[ key ] = null;
            }
        }catch(e:Error){}
}

Glenn is right, there is no such thing as a removeAllListener or listAllListener method. Nevertheless, you could make your custum diplayObject implement the IEventDispatcher interface and keep track of all the listeners added or removed from your object.

This is sort of a hack, but in some (perhaps most cases), you can easily set the display object to null and re-initialize it and then re-configure it with zero visual disruption.

This has the added bonus of removing all event listeners.

Unless you are doing this in an app that already has hundreds of listeners and objects then it should work perfectly fine so long as you can tolerate reconfiguring your display object.

Obviously, you shouldn't do this on anything that is doing something crazy in the constructor like loading data.

function a(){
    mc.addEventListener(Event.ENTER_FRAME,function(){
                       ...
                       }
}

function b(){
    mc.removeEventListener(Event.ENTER_FRAME,function(){});
}

works...

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