Can dispatchEvent() carry arguments in AS3?

耗尽温柔 提交于 2019-12-02 23:47:09

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!