Removing Event Listeners

When you create an event listener, it sits there constantly waiting for the event to happen. You may forget it's even there; but still, it sits patiently, waiting, listening, and using up computer resources in the process. There are a couple of good reasons why you should remove event listeners when they're no longer needed. One is the computer resource issue. It's also possible for a forgotten event listener to foul up some other process when you least expect it.

Ideally, you should remove an event listener whenever your program no longer needs it. For example, in the preceding TimerEvent, you can remove the listener after the TIMER_COMPLETE event triggers. You can place the code to unregister the timer within timerCompleteListener:

timer.removeEventListener(TimerEvent.TIMER_COMPLETE, timerCompleteListener);

The code to remove an event listener is very similar to the code used to register it in the first place. The removeEventListener() function is a method of any object that has a method to addEventListener(). The same parameters that define the event type and the event handler identify the event listener being removed.