当我不知道作为事件处理程序的函数时,如何调用removeEventListener
?
答案 0 :(得分:1)
您应该创建自己的EventDispatcher实现。令人遗憾的是,本机IEventListener原型并没有提供很多有用的方法。
有一个示例代码,说明该实现的样子:
package {
import flash.events.EventDispatcher;
import flash.utils.Dictionary;
/**
* Advanced Event Dispatcher with a ability to remove all listener by event type
* @author Rytis Alekna
*/
public class AdvancedEventDispatcher extends EventDispatcher {
/** This var holds all references to listeners */
protected var eventListenersByType : Dictionary = new Dictionary( true );
/**
* Call this method to remove all listeners of specified type
*/
public function removeEventListenersByEventType ( type : String, useCapture : Boolean = false ) : void {
var key : String = type + ":" + useCapture;
if ( this.eventListenersByType[ key ] && this.eventListenersByType[ key ].lenght > 0 ) {
// copy array of event listeners
var listenersToRemove : Array = this.eventListenersByType[ key ].concat();
// and clear original
this.eventListenersByType[ key ] = [];
// loop over all listeners
for ( var i : int = 0; i < listenersToRemove.length; i++ ) {
this.removeEventListener( type, ( removeEventListenersByEventType[i] as Function ), useCapture );
}
}
}
/**
* Override this method to implement listeners registration by type.
*/
override public function addEventListener(type:String, listener:Function, useCapture:Boolean = false, priority:int = 0, useWeakReference:Boolean = false) : void {
// register with native method
super.addEventListener(type, listener, useCapture, priority, useWeakReference);
// create a key for storage
var key : String = type + ":" + useCapture;
// check if it doesn't already exist
if ( !this.eventListenersByType[ key ] ) {
this.eventListenersByType[ key ] = [];
}
// push listener to our storage
this.eventListenersByType[ key ].push( listener );
}
}
}
否则正如您所提到的,在您的情况下,您只需要触发一次事件,而不是像AS3 Signals那样使用这样一个方便的框架(http://johnlindquist.com/2010/01/21/as3-signals-tutorial/ )
答案 1 :(得分:1)
试试这个:
obj.addEventListener(MouseEvent.CLICK, function( event :Event ):void
{
obj.removeEventListener(MouseEvent.CLICK, arguments.callee );
});
答案 2 :(得分:0)
如果我理解正确,您希望删除所有其他事件处理程序并添加一个。这是不可能的,AFAIK。而且这是非常奇怪的行为,因为你的目标是只有一个事件监听器 - 我最好是防止而不是清理。
考虑使用preventDefault
,stopPropagation
函数或自定义类与您需要的logick(例如,回调而不是事件)。