[转]全局鼠标侦听

所谓的全局鼠标侦听,就是在整个应用中只在一处添加鼠标侦听,从而达来代替应用中漫天飞舞的addEventListener(MouseEvent.。
那么这样做的好处有哪些呢,首先是对鼠标侦听的管理,因为我们不需要在具体需要鼠标事件的地方添加侦听,
所以就不存在忘记移除侦听的情况。
一个应用中有上百个按钮或者更多,少了那么多的addListener和removeListener,会是多么轻松的一件事啊。
当然效率上也会有所提高,我不知道侦听到底会占用多少的系统资源,但是没有侦听总比有侦听占用的系统资源要少吧

那么具体怎么实现呢,你可以在com.codeTooth.actionscript.interaction.mouse.core包中找到,可以看到具体的实现,
当然你可以继续再优化。

用法像是这样,首先有一个文档类,当然也可以是其他地方。

var _mouse:MouseManager;
_mouse = new MouseManager();

// 指定容器,鼠标事件将添加在这个容器上
_mouse.container = this;

然后添加事件
_mouse.addEventType(new EventType(MouseEvent.MOUSE_DOWN));
_mouse.addEventType(new EventType(MouseEvent.MOUSE_UP));
_mouse.addEventType(new EventType(MouseEvent.MOUSE_MOVE));
_mouse.addEventType(new EventType(MouseEvent.MOUSE_OVER));
_mouse.addEventType(new EventType(MouseEvent.MOUSE_OUT));

注册指定的一类对象关注哪些鼠标事件

// 我这里的元素关注了很多鼠标事件
_mouse.addMouseTarget(new MouseTarget(MapElement,[MouseEvent.MOUSE_DOWN,
MouseEvent.MOUSE_UP,
MouseEvent.MOUSE_MOVE,
MouseEvent.MOUSE_OVER,
MouseEvent.MOUSE_OUT]));
// 而悬浮框关注了鼠标划出、划入、和移动事件
_mouse.addMouseTarget(new MouseTarget(IFloatBoxTarget,[MouseEvent.MOUSE_OVER,
MouseEvent.MOUSE_OUT,
MouseEvent.MOUSE_MOVE]));

最后以IFloatBoxTarget为例子看一下,注意这里实现了IMouseTarget接口这是必须要实现的。

public class ClassA extends Sprite
implements IFloatBoxTarget, IMouseTarget
{
// IFloatBoxTarget 的实现省略了 // 实现 IMouseTarget 接口
public function mouseTargetExecute(event:MouseEvent):void
{
if (event.type == MouseEvent.MOUSE_OVER)
{
// do something
}
else if (event.type == MouseEvent.MOUSE_OUT)
{
// do something
}
else if (event.type == MouseEvent.MOUSE_MOVE)
{
// do something
}
}
}

像这样,即使应用中有成百上千个侦听我们也只需要一个addListener就可以了,管理起来也非常方便。比如说我想让整个应用不接受鼠标事件,只需要在MouseManager中设一个开关就行了。你可以修改MouseManager来使得她变得更通用和强大。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值