自定义事件调度



我正在尝试从子类触发一个事件,我有 3 个类;EventHandler, MainClass, SubClass

EventHandler.as

    public class EventHandler extends Event
{
    public static const TEST_EVENT:String = "Test"; 
    public function EventHandler($type:String, $params:Object, $bubbles:Boolean = false, $cancelable:Boolean = false)
    {
        super($type,$params, $bubbles, $cancelable);
        this.params = $params;
    }
    public override function clone():Event
    {
        return new EventHandler(type, this.params, bubbles, cancelable);
    }
}

MainClass.as

        public function MainClass()
    {
        addEventListener(EventHandler.TEST_EVENT, testFunc);
    }

    private function testFunc(e:EventHandler){
        trace("OK");
    }

SubClass.as

private function CustomFunction(event:MouseEvent):void {
        dispatchEvent(new EventHandler(EventHandler.TEST_EVENT,customObject));
    }

我收到验证错误:错误 #1063:flash.events::Event()我的架构师怎么了?谢谢!

定义一个自定义事件,如下所示:

  package com.mysite.events 
  {
     import flash.events.Event;
    public class PendingEvent extends Event 
    {
    public var payload:Object = {};
    public static const CONTENT_COMPLETE:String = "contentComplete";
    public function PendingEvent(type:String, bubbles:Boolean=false, cancelable:Boolean=false) 
    { 
        super(type, bubbles, cancelable);
    } 
    public override function clone():Event 
    { 
        return new PendingEvent(type, bubbles, cancelable);
    } 

}
}

其他地方调度如下:

    var event:PendingEvent = new PendingEvent(PendingEvent.CONTENT_COMPLETE);
    event.payload.someStuff = "stuff";
    event.payload.moreStuff = "moreStuff"
    dispatchEvent(event);

然后在别的地方听:

    this.component.addEventListener(PendingEvent.CONTENT_COMPLETE, componentContentComplete);
    private function componentContentComplete(event:PendingEvent):void 
    {
                    // remove listener
        this.component.removeEventListener(PendingEvent.CONTENT_COMPLETE, componentContentComplete);
                    // do something useful with payload
        var payload:Object = event.payload;
                    trace(payload.someStuff); // stuff
                    trace(payload.moreStuff); // moreStuff
    }

编辑:

显然,您不会将Object用于有效负载,而是创建您选择的另一个类型化类并在该对象上设置属性,但您明白了。

super($type,$params, $bubbles, $cancelable);中删除$params喜欢这个:

public class EventHandler extends Event
{
    public static const TEST_EVENT:String = "Test"; 
    public function EventHandler($type:String, $params:Object, $bubbles:Boolean = false, $cancelable:Boolean = false)
    {
        super($type, $bubbles, $cancelable);
        this.params = $params;
    }
    public var params:Object;
    public override function clone():Event
    {
        return new EventHandler(type, this.params, bubbles, cancelable);
    }
}

相关内容

  • 没有找到相关文章

最新更新