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:
private function handleClick(e:Event):void
{
trace("altKey down: "+e.altKey);
}
But this will:
private function handleClick(e:MouseEvent):void
{
trace("altKey down: "+e.altKey);
}
However so will this (not recommended though, see below):
private function handleClick(e:Event):void
{
trace("altKey down: "+MouseEvent(e).altKey);
}
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).
this is a list of information available from an Event:
this is a list of information available from a MouseEvent:
as you can see, the MouseEvent contains much more specific data for the event than a generic Event object.
something like the following will fail:
private function mouseEventHandler(evt:Event):void
{
trace(evt.localX);
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With