我看到了一个类似这样的问题,但是答案避免了来自课堂内部的回调函数。
我做了一个读取目录(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
}
可以这样做吗?怎么样?
答案 0 :(得分:3)
让您的自定义类扩展EventDispatcher
并发送所需的事件。
例如,对于像Event.Complete
这样的简单事件,只需调度一个新的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;
}
}
}
当此类调度您的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;
}