EventHandler AS3 Class (Removes all EventListeners for an Object)

Hi all,

I came across a blog post today that showed how you can remove all EventListeners from an Object with one function call. It was OK but I modified it and added some more functionality.

Usually I try to remove EventListeners as soon as they’re not needed anymore but this class should help others who are just starting out. I’m not sure if anyone will actually use this but I thought I’d share it anyway! :slight_smile:

There are 4 methods;

addEventListener() - This works in exactly the same way as the default function, I’ve just overridden it to add extra functionality.

removeEventListener() - Same again, works the same way but overridden to add extra functionality.

removeAllEventListeners() - Will remove every EventListener that the Object dispatches.

getAllEventListeners() - Returns an Array of all the EventListeners currently setup for the Object.

import com.lewip.events.EventHandler;

// 'mc' is just a MovieClip located on the stage
var handler:EventHandler = new EventHandler(mc);
handler.addEventListener(MouseEvent.CLICK, onMouseClickHandler);
handler.addEventListener(MouseEvent.MOUSE_OVER, onDummyHandler);
handler.addEventListener(MouseEvent.MOUSE_OUT, onDummyHandler);

function onMouseClickHandler(e:MouseEvent):void
{
	// Returns an Array of Events dispatched by 'mc'
	trace(handler.getAllEventListeners());
	
	// Removes the MOUSE_OUT EventListener
	handler.removeEventListener(MouseEvent.MOUSE_OUT, onDummyHandler);
	
	// Removes all EventListeners dispatched by 'mc'
	handler.removeAllEventListeners();
}

function onDummyHandler(e:MouseEvent):void
{
	// doesn't do anything, for demo purposes only
}

lewi-p