在构思事件机制时,有两个基本问题需要回答。
1) 如何为我的事件创建调度程序实例?
一般选项是:扩展 EventDispatcher,或聚合调度程序实例。
最基本和最常见的做法(官方文档也说明了这一点)是扩展 EventDispatcher 类,从而为您的类提供事件调度功能。
优点:实现简单——只需键入 extends EventDispatcher,就完成了。
缺点:你不能扩展其他东西。显然,这就是为什么许多原生类是 EventDispatcher 的孙子的原因。我猜只是为了省去我们的麻烦。
第二种通用方法是聚合调度程序实例。
package
{
import flash.events.Event;
import flash.events.EventDispatcher;
import flash.events.IEventDispatcher;
public class ClassA implements IEventDispatcher
{
private var dispatcher:EventDispatcher;
public function ClassA()
{
initialize();
}
private function initialize():void
{
dispatcher = new EventDispatcher(this);
}
public function addEventListener(type:String, listener:Function, useCapture:Boolean = false, priority:int = 0, useWeakReference:Boolean = false):void
{
dispatcher.addEventListener(type, listener, useCapture, priority, useWeakReference);
}
public function removeEventListener(type:String, listener:Function, useCapture:Boolean = false):void
{
dispatcher.removeEventListener(type, listener, useCapture);
}
public function dispatchEvent(event:Event):Boolean
{
return dispatcher.dispatchEvent(event);
}
public function hasEventListener(type:String):Boolean
{
return dispatcher.hasEventListener(type);
}
public function willTrigger(type:String):Boolean
{
return dispatcher.willTrigger(type);
}
}
}
注意:我们将聚合类的引用传递给调度程序构造函数。这样做是为了让 event.target 引用您的类实例,而不是调度程序实例本身。
优点:您可以自由扩展您喜欢的任何内容。您可以使用调度程序挂钩做一些技巧,例如维护侦听器列表或类似的东西。
缺点:不像第一种方法那么简单。
2) 我如何通过我的事件传递自定义数据?
一般选项是:在事件实例中传递数据,或仅在事件处理程序中使用 event.target 引用来访问源中的某些数据。
如果您选择通过 event.target 访问所有必要的数据——无需额外的工作,只需将事件处理程序中的此引用转换为适当的类。
If you want to pass some data along with event, you subclass Event, and this class should be publicly visible to the code that handles events, as the answer above states. AS3 is all about strict and strong typing, so why would you resist that?
Overriding clone() method in an Event subclass is only necessary if you are going to redispatch handled events. The official docs say you must do that every time you create a custom event class, just to be safe.