您好,只是想知道是否可以在 AS3 中的非显示列表类中利用事件冒泡。
例如,在应用程序的模型中,有一个包含许多汽车的 City 类。有哪些方法可以将事件监听器附加到 City 对象并接收从子 Cars 冒出的事件。澄清一下,City 和 Car 对象不是显示列表的一部分,它们不是 DisplayObject。那么冒泡可以在显示列表之外以某种方式实现吗?
据我所知,如果不手动将事件监听器附加到每个 Car 对象并从 City 对象重新分派(dispatch)事件,这是不可能的。还有其他人有更清洁的解决方案吗?
最佳答案
这门课是我解决这个问题的方法。基本上让您的类通常扩展 EventDispatcher 而不是扩展 BubblingEventDispatcher
然后调用 addChildTarget( target:BubblingEventDispatcher ) 函数来设置可以从中捕获冒泡事件的子项。
此解决方案为每个事件调度程序使用一个 Sprite ,但每个类仅使用 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;
}
}
}
关于actionscript-3 - 场景图形/显示列表之外的 AS3 事件冒泡,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/662274/