Reputation: 7935
I find addEventListener
method a bit limited. I would like to use another version of it, made by me. I would like to insert a parameter that will tell if a dispatched event can be auto removed, so it will avoid me have to write this in everywhere:
obj.addEventListener(Click, function onClick(e:Event):void {
obj.removeEventListener(Click, onClick); // <--- I want to avoid this
});
Then:
obj.addEventListener(Click, function onClick(e:Event):void {
// no need anymore.
}, true); // <--- see
What approach can I take in order to reach that?
Upvotes: 0
Views: 94
Reputation: 1184
A quick and fairly simple solution to allow for anonymous functions is the arguments.callee property
obj.addEventListener(Event.WHATEVER, function(e:Event)
{
e.currentTarget.removeEventListener(Event.WHATEVER, arguments.callee);
//Do your stuff
}
This creates the event listener and listen function at the same time, in the remove listener, it uses arguments.callee the reference the called function, allowing it to remove itself.
Upvotes: 0
Reputation: 13675
You can always intercept your addEventListener
method call using override with closures:
override public function addEventListener(type:String, listener:Function, useCapture:Boolean = false, priority:int = 0, useWeakReference:Boolean = false):void
{
var self = this;
var weakListener:Function = function(e) {
self.removeEventListener(type, weakListener);
listener(e);
}
super.addEventListener(type, weakListener, useCapture, priority, useWeakReference);
}
Upvotes: 1