1

我看到了一个这样的问题,但是答案避免了使用类内部的回调函数这一点。

我做了一个读取目录(ListaDir)的类,向php服务器端发出请求并处理答案。我希望这样使用:

var Lista:ListaDir = new ListaDir(urltophplibrarythatreadthedirectory); // this is working
Lista.addEventListener(Event.COMPLETE, myHandlerFunc); // this is the dream

function myHandlerFunc(e){
var Res:Object = e.target.data; // The answer in object containing the list and another info
}

可以这样做吗?如何?

4

1 回答 1

3

让您的自定义类扩展EventDispatcher并分派所需的事件。

例如,对于简单的事件,比如Event.Complete简单地发送一个 new Event

package
{
    import flash.events.Event;
    import flash.events.EventDispatcher;

    public class ListaDir extends EventDispatcher
    {
        public function dispatch():void
        {
            dispatchEvent(new Event(Event.COMPLETE));
        }
    }
}

如果您需要发送带有数据的事件,最好创建您的事件类。

自定义事件类

例如,这CustomEvent演示了一个data有效负载对象:

package
{
    import flash.events.Event;

    public class CustomEvent extends Event
    {
        public static const COMPLETE:String = "COMPLETE";

        public var data:*;

        public function CustomEvent(type:String, data:*, bubbles:Boolean=false, cancelable:Boolean=false)
        {
            super(type, bubbles, cancelable);

            if (data)
                this.data = data;
        }
    }
}

ListaDir 类

当此类调度您的CustomEvent时,它可以发送数据的有效负载:

package
{
    import flash.events.Event;
    import flash.events.EventDispatcher;

    public class ListaDir extends EventDispatcher
    {
        public function dispatch():void
        {
            var dataObject:Object = {name: "Example Data"};
            dispatchEvent(new CustomEvent(CustomEvent.COMPLETE, dataObject));
        }
    }
}

执行:

实例化并创建一个事件监听器:

var listaDir:ListaDir = new ListaDir();
listaDir.addEventListener(CustomEvent.COMPLETE, completeHandler);

完成后,检索您的数据对象:

protected function completeHandler(event:CustomEvent):void
{
    var dataObject:* = event.data;
}
于 2013-06-15T22:16:08.900 回答