自定义事件调度

时间:2012-05-24 13:37:14

标签: actionscript-3 event-handling dispatchevent custom-event

我正在尝试从子类中激活一个事件,我有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));

    }

我得到VerifyError:错误#1063:flash.events :::Event() 我的建筑师有什么问题?谢谢!

2 个答案:

答案 0 :(得分:2)

定义一个自定义事件,如:

  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作为你的有效载荷,创建你选择的另一个类型的类,并在那个对象上设置道具,但你明白了。

答案 1 :(得分:1)

$params移除super($type,$params, $bubbles, $cancelable); 像这样:

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);
    }

}