How do I do “onReleaseOutside” in ActionScript 3?

Back in the days of ActionScript 1 and 2 you sometimes wanted to find out when a button or movieclip was clicked, but then the mouse was released outside of that object. This was particularly handy when doing drag and drop since it was (and still is) possible that the user could whip their mouse around and let go of the mouse when the mouse pointer wasn’t actually on top of the clip. If you didn’t listen for the the “onReleaseOutside” event the clip being dragged would now be permanantly stuck a few pixels away from your mouse pointer following it around like a stray dog.

In ActionScript 3 the core mouse related events are CLICK, MOUSE_DOWN, and MOUSE_UP. The overall concept of releasing the mouse but not on top of the display object that received the original MOUSE_DOWN event is intrinsically handled by how the new event system works. Essentially events go through phases – for example when the mouse is pressed the Flash player creates an event and passes that event down from the stage through the display tree to the display object that was actually clicked on. If that display object doesn’t catch the event it then bubbles back up the tree to see if any of those display objects want to handle it. If the event bubbles all the way up the stage and it isn’t handled it is just destroyed.

Thus, you can find out when the mouse was released, no matter what display object it was over, by listening for a MOUSE_UP event coming from the stage. Just as always you should only listen for this event when you need it – which in this case is easy to do because you can start listening when the the MOUSE_DOWN event is handled and stop listening when the MOUSE_UP event is handled.

import flash.events.MouseEvent;

function dragPin(evt:MouseEvent):void {
	pin.startDrag();
	stage.addEventListener(MouseEvent.MOUSE_UP, dropPin);
}

function dropPin(evt:MouseEvent):void {
	pin.stopDrag();
	stage.removeEventListener(MouseEvent.MOUSE_UP, dropPin);
}

pin.addEventListener(MouseEvent.MOUSE_DOWN, dragPin);

no comments

  • No comments yet.