Search code examples
actionscript-3apache-flexevent-handlingdispatcheventevent-listener

AS3 dispatchEvent not working


I've searched other examples of dispatching events and none of them have helped me.

Here is what I have so far. I know that the event listener is added successfully, but the event is never dispatched.

In a .mxml file:

function foo():void {

    var eventClassObj:MyEventClass = new MyEventClass();


}

In a separate .as file:

public class MyEventClass extends EventDispatcher 
{

    public function MyEventClass(target:flash.events.IEventDispatcher = null) 
    {

                    //ADD EVENT LISTENER
        this.addEventListener("test", testFunc, true);



                    //DEBUGGING PRINT STATEMENTS
        var str:String;
        if (this.hasEventListener("test")) {
                str = "EVENT LISTENER ADDED";
        } else {
                str = "NO LISTENER";
        }

        ExternalInterface.call("console.log", str);

                    //DISPATCH EVENT
        this.dispatchEvent(new Event("test", true));
    }


    //THIS MUST EXECUTE WHEN EVENT DISPATCHED
    private function testFunc(e:Event):void {
        ExternalInterface.call("console.log", "dispatch event successful");
    }
}

I am completely new to ActionScript3. Do you know why the event is never dispatched? My output in the console for running this would only be:

EVENT LISTENER ADDED

while my expected output is:

EVENT LISTENER ADDED
dispatch event successful

I don't see why this wouldn't work.


Solution

  • Problem stems from the way how you add event listener. You set useCapture as true and such setting prevents listener from reaction to bubbling event.

    If you change following row:

    this.addEventListener("test", testFunc, true);
    

    to:

    this.addEventListener("test", testFunc);
    

    event will be handled by your testFunc.