Skip to content

Flash/AS3: Universal onMouseUpOutside solution

2010 June 28
tags: ,
by Tedb0t

As has been observed many times in the years since its debut, ActionScript 3.0 has no “onMouseUpOutside” event, meaning that if you press the mouse button down while over an object, move the mouse, then release the mouse button, that button will not generate a MOUSE_UP event.

This problem is not too hard to solve for a single object, in which case you can hard-code any callbacks you might need. ┬áThe problem becomes really complicated if you need to pass in arguments to the event handler, i.e. if you’re writing a function that automatically initializes an arbitrary object.

The solution to this is not elegant, not simple, and I’m not convinced it’s 100% perfect, but in practice so far it seems to work pretty well. This example initializes a display object that has a drop shadow and animates the mouse down state and calls a callback on release.

import flash.utils.Dictionary;

var _lastButton;
var _callbackDict = new Dictionary();

function initShadowButton(which:Object, callback){
	which.buttonMode = true;
	which.useHandCursor = true;

	which.addEventListener(MouseEvent.MOUSE_DOWN, function(e:MouseEvent){
		_buttonShadow = e.currentTarget.filters;
		_buttonShadowDistance = _buttonShadow[0].distance;
		e.currentTarget.filters = [];
		e.currentTarget.x += _buttonShadowDistance;
		e.currentTarget.y += _buttonShadowDistance;
		_lastButton = e.currentTarget;
		_callbackDict[_lastButton] = callback;

		stage.addEventListener(MouseEvent.MOUSE_UP, onMouseUpOutside);
	});
}

function onMouseUpOutside(e:MouseEvent){
	_lastButton.filters = _buttonShadow;
	_lastButton.x -= _buttonShadowDistance;
	_lastButton.y -= _buttonShadowDistance;
	stage.removeEventListener(MouseEvent.MOUSE_UP, onMouseUpOutside);
	_callbackDict[_lastButton](e);
}

Related Posts:


No comments yet

Leave a Reply

Note: You can use basic XHTML in your comments. Your email address will never be published.

Subscribe to this comment feed via RSS