如何使用添加的数据调度事件 - AS3

use*_*521 9 apache-flex flash events actionscript-3 dispatchevent

任何人都可以给我一个简单的例子,说明如何在actionscript3中发送一个附加了对象的事件,比如

dispatchEvent( new Event(GOT_RESULT,result));
Run Code Online (Sandbox Code Playgroud)

result是一个我希望与事件一起传递的对象.

Tom*_*rov 31

如果您想通过事件传递对象,则应创建自定义事件.代码应该是这样的.

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);
    }
}
Run Code Online (Sandbox Code Playgroud)

然后你就可以使用上面的代码:

dispatchEvent(new MyEvent(MyEvent.GOT_RESULT, result));
Run Code Online (Sandbox Code Playgroud)

你必要时听这个事件.

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.
}
Run Code Online (Sandbox Code Playgroud)

  • 顺便说一句,我创建了一个在线工具来创建自定义as3事件http://projects.stroep.nl/EventGenerator/它可以帮助设置更快.随意使用. (3认同)