开发者

How do I handle a custom event in ActionScript 3?

I've created an Event Handler/Listener like so:

import flash.events.Event;

public class DanielEvent extends Event {

    public var data:*;
    public static const APP_STARTED:String = "APP_STARTED";

    public function DanielEvent(n:String, data:*){
        this.data = data;
        super(n)
    }
}

Listening to an event using:

addEventListener(DanielEvent.APP_STARTED, appStarted);

Dispatching an event by:

dispatchEvent(new D开发者_如何学CanielEvent("APP_STARTED", "test"))

And receiving the data by:

private function appStarted(e:Event){
    trace(e.data)
}

But I get the error:

Access of possibly undefined property data through a reference with static type flash.events:Event.


You have to use your custom event type in the event handler, if you want to access the data property:

private function appStarted(e:DanielEvent): void { 
    trace(e.data);
}


your event handler is passed a DanielEvent, not an Event:

private function appStarted(e:DanielEvent):void
    {
    trace(e.data);
    }

also. you should also use your constant for your dispatch instead of passing a string, like you've done for your listener:

dispatchEvent(new DanielEvent(DanielEvent.APP_STARTED, "test"));

and don't forget to override clone() if you are planning on dispatching that event more than once.

public override function clone():Event
     {
     return new DanielEvent(n, data);
     }
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜