実際にこれを行うのはかなり簡単です。クラスのカップルはあなたを得る必要があります。
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 + "]";
}
}
を次に、Iは、2つの他のベースクラスを使用する:次のように最初は、Event
クラスです。 1つは通常のオブジェクト用で、拡張する必要があるオブジェクトの場合は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 { }
}
は単にディスパッチャまたは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));
}
}
もう1つは、そのイベントを聴きたいときです。 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!
}
}
このファイルをすべて私の古いファイルから正しくコピーして貼り付けてください。これがあなたのために働くことを願っています。
ありがとう! – Iain
@Matt W、なぜ$記号がありますか? – Simsons
@Subhenは、ローカル変数とインスタンス変数から関数のパラメータを表すために使用していた、古いコードスタイルの規約だけです。 –