Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
427 views
in Technique[技术] by (71.8m points)

actionscript 3 - How to dispatch an event with added data - AS3

Can any one give me a simple example on how to dispatch an event in actionscript3 with an object attached to it, like

dispatchEvent( new Event(GOT_RESULT,result));

Here result is an object that I want to pass along with the event.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

In case you want to pass an object through an event you should create a custom event. The code should be something like this.

public class MyEvent extends Event
{
    public static const GOT_RESULT:String = "gotResult";

    // this is the object you want to pass through your event.
    public var result:Object;

    public function MyEvent(type:String, result:Object, bubbles:Boolean=false, cancelable:Boolean=false)
    {
        super(type, bubbles, cancelable);
        this.result = result;
    }

    // always create a clone() method for events in case you want to redispatch them.
    public override function clone():Event
    {
        return new MyEvent(type, result, bubbles, cancelable);
    }
}

Then you can use the code above like this:

dispatchEvent(new MyEvent(MyEvent.GOT_RESULT, result));

And you listen for this event where necessary.

addEventListener(MyEvent.GOT_RESULT, myEventHandler);
// more code to follow here...
protected function myEventHandler(event:MyEvent):void
{
    var myResult:Object = event.result; // this is how you use the event's property.
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...