Way to remove unknown event listeners from objects

actionscript-3

I want to have a reusable button which can be registered for one of many different callbacks, determined by an external source. When a new callback is set, I want to remove the old. I also want to be able to clear the callback externally at any time.

public function registerButtonCallback(function:Function):void
{
  clearButtonCallback();

  button.addEventListener(MouseEvent.CLICK, function, false, 0, true);
}

public function clearButtonCallback():void
{
  if (button.hasEventListener(MouseEvent.CLICK) == true)
  {
    // do something to remove that listener
  }
}

I've seen suggestions on here to use "arguments.callee" within the callback, but I don't want to have that functionality tied to the callback – for example, I might want to be able to click the button twice.

Suggestions?

Best Solution

I am presuming that you want only one callback function at any given time. If that's teh case then why not have a single callback function associated with the click event on the button which itself called a function and have that function be settable...

<mx:Button click="doCallback()" .../>

public var onClickFunction:Function = null;
private function doCallback():void
{
    if (onClickFunction != null)
    {
        onClickFunction(); // optionally you can pass some parameters in here if you match the signature of your callback
    }
}

A consumer of your control which houses your button would set the onClickFunction with the appropriate function. In fact you could set it as often as you liked.

If you wanted to go one step further you could subclass the AS3 Button class and wrap all of this inside it.

Related Question