微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

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 + "]";
    }
}

然后,我使用另外两个基类.一个用于常规对象,另一个用于需要扩展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 { }
}

只需使用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!
    }
}

希望我能从我的旧文件中正确复制并粘贴所有这些内容!希望这对你有用.

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐