问题
Behold this example:
addEventListener("myEventType", myFunction("argument"));
function myFunction(args:String):Function {
return function(evt:Event):void {
trace(evt.currentTarget, "has", args);
};
}
dispatchEvent(new Event("myEventType", true));
It works.
Can I do something similar, but passing "argument"
through dispatchEvent()
?
It'd be very handy in a situation where dispatchEvent()
is in a wholly separated class from addEventListener()
and myFunction()
.
I'll be needing this a lot, so I want to do it without creating a custom event class for every situation.
回答1:
You can use native flash.events.DataEvent
for passing String
parameter or create custom DataEvent
with data:*
property in all situations where you need to pass parameters to event handler.
If you want to customize the behavior of event listener in the place of adding event listener you can create "listener" object for holding this custom parameters (but I think this technique is more complicated than custom events):
addEventListener("myEventType", new EventListener("param1").onEvent);
, whereEventListener
is the class like this:
public class EventListener
{
private var params:*;
public function EventListener(params:*)
{
this.params = params;
}
public function onEvent(event:Event):void
{
trace("onEvent, params = ", params);
}
}
回答2:
You could take a look at Signals (https://github.com/robertpenner/as3-signals). They are an alternative to Events and you can send whatever extra params you want with a Signal.
来源:https://stackoverflow.com/questions/14028444/can-dispatchevent-carry-arguments-in-as3