AS2 → AS3: Using Mouse Events

Download Example Files

Gone are the days of having to create objects to act as listeners for mouse events. The nasty, unruly way of AS2 has been replaced like everything else with the AS3 event model and writing mouse listeners is similar to everything else you're now used to in AS3.

The AS2 version was kind of dirty:

Actionscript:
  1. var mListener:Object = new Object();
  2.  
  3. mListener.onMouseDown = function():Void
  4. {
  5.     trace("MOUSE DOWN!");
  6. };
  7.  
  8. mListener.onMouseUp = function():Void
  9. {
  10.     trace("MOUSE UP!");
  11. };
  12.  
  13. mListener.onMouseMove = function():Void
  14. {
  15.     trace("MOUSE MOVING!");
  16. };
  17.  
  18. Mouse.addListener(mListener);

The AS3 version is neat and tidy, just like everything else:

Actionscript:
  1. stage.addEventListener(MouseEvent.MOUSE_DOWN, doMouseDown, false, 0, true);
  2. stage.addEventListener(MouseEvent.MOUSE_UP, doMouseUp, false, 0, true);
  3. stage.addEventListener(MouseEvent.MOUSE_MOVE, doMouseMove, false, 0, true);
  4.  
  5. function doMouseDown($evt:MouseEvent):void
  6. {
  7.     trace("MOUSE DOWN!");
  8. }
  9.  
  10. function doMouseUp($evt:MouseEvent):void
  11. {
  12.     trace("MOUSE UP!");
  13. }
  14.  
  15. function doMouseMove($evt:MouseEvent):void
  16. {
  17.     trace("MOUSE IS MOVING!");
  18. }

If you found this post useful, please consider leaving a comment, subscribing to the feed, or making a small donation.

2 Comments

Your AS3 example convert exactly to this in AS2 :

addListener(_root); // or addListener(_this);
onMouseDown = function():Void
{
trace("MOUSE DOWN!");
}
onMouseUp = function():Void
{
trace("MOUSE UP!");
}
onMouseMove = function():Void
{
trace("MOUSE MOVING!");
}

What is the difference? what is neat and tidy?
In AS3, you declare your functions handlers on _root, and add listener one by one with lots of evident stuff added, that is, exept that.. exactly the same.

sorry, this one is even closer to your AS3 version:

Mouse.addListener(_root);

function onMouseDown():Void
{
trace("MOUSE DOWN!");
}
function onMouseUp():Void
{
trace("MOUSE UP!");
}
function onMouseMove():Void
{
trace("MOUSE MOVING!");
}

AS3.. or how to reinvent a simple wheel more complex

Leave a comment

(required)

(required)