Some Pixels en / pt

How to remove Event Listeners with parameters / closure?

On my last post, shaokai asked me how to remove those event handlers added dynamically with parameters and I think it's a really good question, so I'm posting the solution here too.

Actually, I never tried to remove the listener, but you can't do this the same way you add the listener. So I found two different solutions to this problem. First, but maybe not the best solution, you can keep a reference to your handler, like this:

// Keep the reference
var myHandler:Function = buttonHandler(0x0000FF);

// Add the listener
myComponent.addEventListener(MouseEvent.CLICK, myHandler);

// Remove the listener
myComponent.removeEventListener(MouseEvent.CLICK, myHandler);

This solution is valid when you can keep references to your handlers, but when you have many handlers with different parameters, it's hard to keep all the references. So I found a generic solution to remove event listeners, so you can do this, inside your handler function:

private function buttonHandler(color:uint):Function
{
    return function(event:MouseEvent):void
    {
        box.setStyle("backgroundColor", color);

        // Remove the handler
        event.currentTarget.removeEventListener(event.type, arguments.callee);
    }
}