Wednesday, April 15, 2009

Removing anonymous function from an event listener

Hey guys and gals, quick lesson in flex. One popular thing to do is use something called an anonymous function with eventListeners when you want to pass the function something more than just the event. You would typically just say:

myObj.addEventListener(Event.ENTER_FRAME, function(a_event:Event):void{someotherFunc(a_event, additionalArgs);});

But this sucks if you are going to want to remove the listener. So something you can do is the following. You can create a function variable (func), then set the anonymous function to this var. Then the second function that you ultimately want to call (func2) will have an optional parameter ‘myHackFunc’ that will be the variable that you created (func). Then you just call remove event listener on ‘myHackFunc’.

I have heard of other ways of doing this, mainly, using ‘arguments.callee’ This causes my app to die, but the way described above, and shown below, seems to work all the time. Hope it helps!


public function myFunc1():void{
var func:Function = function(a:Event):void{ func2 (a, some_args, func)};
i.addEventListener(Event.ENTER_FRAME, func);
}

public function func2(a_event:Event, some_args:*, myHackFunc:Function = null):void{
a_event.currentTarget.removeEventListener(Event.ENTER_FRAME, myHackFunc);
}


Oh, or you could just go and use a custom event class... but that isn't the point of this exercise :P