O'Reilly logo

Learning ActionScript 3.0 by Zevan Rosser, Rich Shupe

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

Removing Event Listeners

While event listeners make most event handling easy to add and maintain, leaving them in place when unneeded can wreak havoc. From a logic standpoint, consider what could happen if you kept an unwanted listener in operation. Imagine a weeklong promotion for radio station 101 FM, which rewards customer number 101 who enters a store each day of that week. The manager of the store is set up to listen for "customer enter" events and, when customer 101 enters the store, oodles of prizes and cash are bestowed upon the lucky winner. Now imagine if you left that listener in place after the promo week was over. Oodles of prizes and cash would continue to be awarded at great, unexpected expense.

Unwanted events are not the only problem, however. Every listener created occupies a small amount of memory. Injudiciously creating many event listeners, without cleaning up after yourself, can result in a memory leak. Therefore, it's a good idea to remove listeners when you know they will no longer be needed.

To do so, you simply need to use the removeEventListener() method. By specifying the owner of the relevant event and the listener function that is triggered, you can remove that listener so it no longer reacts to future events. The removeEventListener() method requires two parameters: the event and function specified when the listener was created. Specifying the event and function is important because you may have multiple listeners set up for the same event.

Let's add ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required