实际上,这很容易做到。几节课应该能让你继续前进。第一个是Event 类,如下:
class com.rokkan.events.Event
{
public static var ACTIVATE:String = "activate";
public static var ADDED:String = "added";
public static var CANCEL:String = "cancel";
public static var CHANGE:String = "change";
public static var CLOSE:String = "close";
public static var COMPLETE:String = "complete";
public static var INIT:String = "init";
// And any other string constants you'd like to use...
public var target;
public var type:String;
function Event( $target, $type:String )
{
target = $target;
type = $type;
}
public function toString():String
{
return "[Event target=" + target + " type=" + type + "]";
}
}
然后,我使用另外两个基类。一个用于常规对象,一个用于需要扩展MovieClip 的对象。首先是非MovieClip 版本...
import com.rokkan.events.Event;
import mx.events.EventDispatcher;
class com.rokkan.events.Dispatcher
{
function Dispatcher()
{
EventDispatcher.initialize( this );
}
private function dispatchEvent( $event:Event ):Void { }
public function addEventListener( $eventType:String, $handler:Function ):Void { }
public function removeEventListener( $eventType:String, $handler:Function ):Void { }
}
接下来是MovieClip 版本...
import com.rokkan.events.Event;
import mx.events.EventDispatcher;
class com.rokkan.events.DispatcherMC extends MovieClip
{
function DispatcherMC()
{
EventDispatcher.initialize( this );
}
private function dispatchEvent( $event:Event ):Void { }
public function addEventListener( $eventType:String, $handler:Function ):Void { }
public function removeEventListener( $eventType:String, $handler:Function ):Void { }
}
只需使用 Dispatcher 或 DispatcherMC 扩展您的对象,您就可以像 AS3 一样分派事件和侦听事件。只有几个怪癖。例如,当您调用 dispatchEvent() 时,您必须传入对调度事件的对象的引用,通常只需引用对象的 this 属性即可。
import com.rokkan.events.Dispatcher;
import com.rokkan.events.Event;
class ExampleDispatcher extends Dispatcher
{
function ExampleDispatcher()
{
}
// Call this function somewhere other than within the constructor.
private function notifyInit():void
{
dispatchEvent( new Event( this, Event.INIT ) );
}
}
另一个怪癖是当您想监听该事件时。在 AS2 中,您需要使用 Delegate.create() 来获取事件处理函数的正确范围。例如:
import com.rokkan.events.Event;
import mx.utils.Delegate;
class ExampleListener
{
private var dispatcher:ExampleDispatcher;
function ExampleDispatcher()
{
dispatcher = new ExampleDispatcher();
dispatcher.addEventListener( Event.INIT, Delegate.create( this, onInit );
}
private function onInit( event:Event ):void
{
// Do stuff!
}
}
希望我从旧文件中正确复制并粘贴了所有这些内容!希望这对你有用。