I am always trying to improve my programming practices and this one habit of mine has gotten me thinking that maybe it isn’t the best approach. When handling MouseEvent function calls I have a tendency to use Event over MouseEvent in the params.
Example:
mc.addEventListener(MouseEvent.CLICK, handleClick);
private function handleClick(e:Event):void
{
trace(e.currentTarget.name + " was Clicked");
}
Is there some functionality or properties inside of MouseEvent unavailable in the Event class that would make using MouseEvent more of a necessity? The only reason I can think of on my own is to keep your events/functions params strongly-typed.
If you don’t type the parameter as MouseEvent, you will just have to cast it as a MouseEvent to access properties that are specific to the MouseEvent subclass. For example:
This won’t work:
But this will:
However so will this (not recommended though, see below):
Generally speaking, you want your listener parameter type to be only as general as is necessary, so that if your function is called with the wrong type of event, it fails in an obvious way.
Your example works because currentTarget is a property of the Event base class. But there is nothing stopping your handleClick from receiving and responding to an IOErrorEvent or KeyboardEvent, and doing something you don’t expect without failing (e.g. if you accidentally set it up to listen to something other than a MouseEvent, which you would not do deliberately, but could happen if you copy-paste the addEventListener line of code and change the event type but forget to change the handler function… these things do happen).