Skip to content

Posts from the ‘Flash / AS3’ Category

29
Oct

AS3 Click Handler – How to limit click occurrence

I’ve always found the way flash treats a click-event quite annoying.
No matter when you release the left mouse-button, flash will always trigger a Click-Event, even if you keep waiting for seconds.

In its original matter, clicking was meant to be a short order of Pressing the Mouse Down and letting go of it!
Furthermore I wouldn’t want to have the system fire a Click-Event when moving a particular amount of pixels in between my Mouse-Down and Mouse-Up phases!

To meet these needs I wrote myself a Class that would handle all the forespoken concepts!

package Global.Utils {

	import flash.events.MouseEvent;
	import flash.geom.Point;
	import flash.display.DisplayObject;

	public class ClickHandler {

		public static var ClickMaxMove:Number = 5;
		public static var ClickMaxTime:Number = 100;

		private var StoreMousePosition:Point;
		private var StoreTime:Number;

		public function ClickHandler(StageInstance:DisplayObject) {
			StageInstance.stage.addEventListener(MouseEvent.MOUSE_DOWN, OnMouseDown, true);
			StageInstance.stage.addEventListener(MouseEvent.CLICK, OnClick, true);
		}

		private function OnMouseDown(event:MouseEvent):void {
			StoreMousePosition = new Point(event.currentTarget.stage.mouseX, event.currentTarget.stage.mouseY);
			StoreTime = new Date().getTime();
		}

		private function OnClick(event:MouseEvent):void {
			var Distance:Number = Math.abs(StoreMousePosition.x - event.currentTarget.stage.mouseX) + Math.abs(StoreMousePosition.y - event.currentTarget.stage.mouseY);
			if (Distance > ClickMaxMove) Stop(event);
			if ((StoreTime - new Date().getTime()) > ClickMaxTime) Stop(event);
		}

		private function Stop(event:MouseEvent):void {
			event.stopImmediatePropagation();
			event.stopPropagation();
			event.preventDefault();
		}

	}

}

 

You can call this ClickHandler at any time by passing it the stage or any child that’s already been added to the stage!
For the purpose of this Handler you should respectively call it at the beginning of your Application!

Still, no need to keep an instance of it, since all important events will be added to the main stage.

By keeping the Core-Variables ClickMaxMove and ClickMaxTime static you can Adjust them when needed during runtime (e.g. User-Settings, PHP-Query-String, etc.)

import Global.Utils.ClickHandler;

new ClickHandler(stage);
ClickHandler.ClickMaxMove = 10;
ClickHandler.ClickMaxTime = 200;

 

Any questions, comments and further suggestions for improving this Class are welcome and appreciated!