as3自己实现双击
as3中有双击事件。自己用单击事件实现了一个双击,来满足一些特殊的需求。
直接上demo:双击
主要代码:
HDoubleClick.as
package com.hanyeah.events
{
import flash.display.Stage;
import flash.events.EventDispatcher;
import flash.events.MouseEvent;
import flash.utils.setTimeout;
import flash.utils.clearTimeout;
import flash.utils.clearTimeout;
import com.hanyeah.events.HEvent;
public class HDoubleClick extends EventDispatcher
{
private var stage:Stage;
private var delay:Number = 300;
private var lastE:MouseEvent;
private var interval:uint;
public function HDoubleClick(stage:Stage)
{
this.stage = stage;
stage.addEventListener(MouseEvent.CLICK, clickHandler);
}
private function clickHandler(e:MouseEvent):void
{
if (lastE)
{
//
if (interval)
{
clearTimeout(interval);
interval = 0;
}
//
if (lastE.stageX == e.stageX && lastE.stageY == e.stageY)
{ //虽然stageX、stageY是Number类型,但是都是整数,所以这么判断没问题
//两次点击是在同一个位置,认为是双击(不考虑点击的目标是否相同)
var me:HEvent = new HEvent(HEvent.DOUBLE_CLICK, [lastE, e], false, false);
dispatchEvent(me);
lastE = null;
}
else
{
//两次点击不是在同一个位置
lastE = e;
interval = setTimeout(clearE, delay);
}
}
else
{
lastE = e;
interval = setTimeout(clearE, delay);
}
}
/**
* 超时清空存储的MouseEvent
*/
private function clearE():void
{
interval = 0;
lastE = null;
}
public function destroy():void
{
stage.removeEventListener(MouseEvent.CLICK, clickHandler);
stage = null;
if (interval)
{
clearTimeout(interval);
interval = 0;
}
}
}
}Main.as
package {
import com.hanyeah.events.HDoubleClick;
import com.hanyeah.events.HEvent;
import fl.controls.TextArea;
import flash.display.MovieClip;
import flash.events.MouseEvent;
import flash.text.TextField;
public class Main extends MovieClip {
public var tf:TextArea;
public function Main() {
// constructor code
//stage.addEventListener(MouseEvent.CLICK, clickHandler);
var doubleClick:HDoubleClick = new HDoubleClick(stage);
doubleClick.addEventListener(HEvent.DOUBLE_CLICK, doubleClickHandler);
}
private function doubleClickHandler(e:HEvent):void
{
var arr:Array = e.data as Array;
showMsg("============================");
showMsg(arr[0])
showMsg(arr[1])
}
private function showMsg(msg:String):void {
trace(msg);
tf.appendText(msg + "\n");
}
private function clickHandler(e:MouseEvent):void
{
trace(e.stageX, e.stageY);
}
}
}实例化HDoubleClick时传入stage对象,然后用HDoubleClick对象侦听HEvent.DOUBLE_CLICK事件,当舞台上发生双击事件时,会触发事件。HEvent对象的data属性是一个数组,包含两次点击的MouseEvent对象,如果想要判断双击是否发生在一个目标对象上,可以对比两个MouseEvent对象的target。