In this tutorial, you will learn how to create a basic event listener, which includes an understandable name, how to properly cast the calling object and how to efficiently determine certain type of events that’s currently dispatching.


There are infinite ways of naming a listener. Anyone can name it mouseEventListener, onMouseEventListener or onMouseEventDispatch. On my end, I typically name my event listeners according to their class names. For mouse events, I name it mouseEventListener.

public final function mouseEventListener(e:MouseEvent):void{}

Meanwhile, comparing different type of events that fired the event can be done like so:

public final function onMouseEvent(e:MouseEvent):void{
	switch(e.type){
		case MouseEvent.MOUSE_DOWN:
			//
		break;
		case MouseEvent.MOUSE_UP:
			//
		break;
		case MouseEvent.CLICK:
			//
		break;
	}
}

The Event.target method is a generic object type. This makes it dynamic but slow since Flash has to determine its correct data type. Also there are instances wherein you want to display the properties of the target object that is firing the event regardless of its phases. You can do so by casting it to its correct data type.

public final function onMouseEvent(e:MouseEvent):void{
	var i:Item = Item(e.target);
	switch(e.type){
		case MouseEvent.CLICK:
			i.visible = false;
		break;
	}
}

Congratulations. You have successfully created an efficient and easy to read event listener.

Advertisements