您好,只是想知道是否可以在 AS3 中的非显示列表类中利用事件冒泡。
例如,在应用程序的模型中,有一个包含许多汽车的 City 类。有哪些方法可以将事件侦听器附加到 City 对象并接收从子 Cars 冒出的事件。澄清一下,City 和 Car 对象不是显示列表的一部分,它们不是 DisplayObject。那么冒泡可以在显示列表之外以某种方式实现吗?
据我所知,如果不手动将事件侦听器附加到每个 Car 对象并从 City 对象重新分派事件,这是不可能的。还有其他人有更清洁的解决方案吗?
这堂课是我解决这个问题的方法。基本上让您的类通常扩展 EventDispatcher 而不是扩展 Bubbling EventDispatcher
然后调用 addChild Target( target:Bubble EventDispatcher ) 函数来设置可以从中捕获冒泡事件的子项。
此解决方案为每个事件调度程序使用一个精灵,但每个类仅使用 1 个字节的额外内存
package
{
import flash.display.Sprite;
import flash.events.Event;
import flash.events.EventDispatcher;
public class BubblingEventDispatcher extends EventDispatcher
{
//We have to use a sprite to take advantage of flash's internal event bubbling system
private var sprite:Sprite;
public function BubblingEventDispatcher()
{
//initialize our sprite
sprite = new Sprite();
}
public override function addEventListener(type:String, listener:Function, useCapture:Boolean=false, priority:int=0, useWeakReference:Boolean=false):void
{
sprite.addEventListener( type, listener, useCapture, priority, useWeakReference );
}
public override function dispatchEvent(event:Event):Boolean
{
return sprite.dispatchEvent( event );
}
//We must add child targets if we want to take advantage of the bubbling
public function addChildTarget( target:BubblingEventDispatcher ):void
{
sprite.addChild( target.eventTarget as Sprite );
}
public function get eventTarget():EventDispatcher
{
return sprite;
}
}
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)