/customers/iconara.net/iconara.net/httpd.www/blog/wp-content/plugins/wp-super-cache/wp-cache-phase1.php Iconara » A generic way to remove an event listener

A generic way to remove an event listener

This might be obvious to everyone, but I thought I’d share a snipplet containing a generic way of removing an event listener:

event.currentTarget.removeEventListener(event.type, arguments.callee)

Place it in your handler function, I prefer to put mine on the first line.

It’s useful in situations where you want to stop listening after the first event has fired, for example. You can use it when the listener is an anonymous inner function, if you don’t know the type of the event, if the dispatcher is unknown or any combination of these.

Most of the time using weak references is probably more appropriate, but in some situations the snipplet above is handy.

A more complete example:

function registerHandler( handler : Function ) : void {
  dispatcher.addEventListener("somethingChanged", handler);
}

// ...

registerHandler(somethingChangedHandler);

// ...

function somethingChangedHandler( event : Event ) : void { event.currentTarget.removeEventListener(event.type, arguments.callee);

performActionInResponseToEvent(); }

If we assume that the three parts of the code above are separated so that the first and the last don’t know about each other, but the middle part knows about both, we can see that the generic way of removing an event listener is more or less the only way to do it.

6 Responses to “A generic way to remove an event listener”

  1. elSuricatoRojo Says:

    Is this example is based on AS2?

  2. Theo Says:

    No.

  3. Mark Ledford :: handy way of removing event listeners via arguments.callee Says:

    [...] Theo’s entry reminded me how useful this can be especially when using an anonymous function as a one time callback. Try it out: [...]

  4. Jason Says:

    thanks a lot for this dude!

  5. Clay Says:

    Very helpful, thanks for the tip

  6. Maarten Merken » Remove All Eventlisteners from an Actionscript 3.0 Component, A Workaround Says:

    [...] can’t all the credit for it, you can find more details here  January 16th, 2010  Maarte   No [...]

Leave a Reply