Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

AS3 : Why use MouseEvent as function Param when Event works fine?

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.

like image 309
Paul Parker Avatar asked Apr 08 '11 15:04

Paul Parker


2 Answers

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).

like image 84
Adam Smith Avatar answered Sep 28 '22 03:09

Adam Smith


this is a list of information available from an Event:

  • type:String
  • bubbles:Boolean
  • cancelable:Boolean

this is a list of information available from a MouseEvent:

  • type:String
  • bubbles:Boolean
  • cancelable:Boolean
  • localX:Number
  • localY:Number
  • relatedObject:InteractiveObject
  • ctrlKey:Boolean
  • altKey:Boolean
  • shiftKey:Boolean
  • buttonDown:Boolean
  • delta:int
  • commandKey:Boolean
  • controlKey:Boolean
  • clickCount:int

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);
}
like image 43
Chunky Chunk Avatar answered Sep 28 '22 04:09

Chunky Chunk