Iai*_*ain 8 flash actionscript-2 actionscript-3
我喜欢AS3事件模型 - 它有助于保持我的代码清洁和失败耦合.当我以前在AS2项目上工作时,我的代码不是那么整洁,而且类更依赖于彼此.由于AS2对范围的奇怪处理,我从未真正开始使用AS2事件系统.
由于我偶尔还要在AS2工作,我的问题是:
有没有人设法在AS2中模拟AS3事件API,如果没有,那么监听和调度事件以及处理范围的最佳做法是什么?
实际上很容易做到这一点.几个课程应该让你去.第一个是一个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 + "]";
}
}
Run Code Online (Sandbox Code Playgroud)
然后,我使用另外两个基类.一个用于常规对象,另一个用于需要扩展的对象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 { }
}
Run Code Online (Sandbox Code Playgroud)
接下来的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 { }
}
Run Code Online (Sandbox Code Playgroud)
只需使用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 ) );
}
}
Run Code Online (Sandbox Code Playgroud)
另一个怪癖是你想要听那个事件.在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!
}
}
Run Code Online (Sandbox Code Playgroud)
希望我从旧文件中正确复制并粘贴所有这些内容!希望这对你有用.
| 归档时间: |
|
| 查看次数: |
8172 次 |
| 最近记录: |