任何人都可以给我一个简单的例子,说明如何在 actionscript3 中调度一个事件,并附加一个对象,比如
dispatchEvent( new Event(GOT_RESULT,result));
这result
是我想与事件一起传递的对象。
任何人都可以给我一个简单的例子,说明如何在 actionscript3 中调度一个事件,并附加一个对象,比如
dispatchEvent( new Event(GOT_RESULT,result));
这result
是我想与事件一起传递的对象。
如果您想通过事件传递对象,您应该创建一个自定义事件。代码应该是这样的。
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);
}
}
然后你可以像这样使用上面的代码:
dispatchEvent(new MyEvent(MyEvent.GOT_RESULT, result));
你在必要时收听这个事件。
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.
}
这篇文章有点旧,但如果它可以帮助某人,你可以像这样使用 DataEvent 类:
dispatchEvent(new DataEvent(YOUR_EVENT_ID, true, false, data));
如果设计得当,您不必将对象传递给事件。
相反,您应该在调度类上创建一个公共 var。
public var myObject:Object;
// before you dispatch the event assign the object to your class var
myObject = ....// whatever it is your want to pass
// When you dispatch an event you can do it with already created events or like Tomislav wrote and create a custom class.
// in the call back just use currentTarget
public function myCallBackFunction(event:Event):void{
// typecast the event target object
var myClass:myClassThatDispatchedtheEvent = event.currentTarget as myClassThatDispatchedtheEvent
trace( myClass.myObject )// the object or var you want from the dispatching class.