Search code examples
flashactionscript-3delegation

flash AS3 event dispatching


I'm very new to Flash, and I am having some trouble:

So I have my class Main that imports a class, NavMenu. In there is an event for a clicked item that runs a function where I write:

dispatchEvent(new Event('my_event'));

In my Main class, in the constructor I have declared

addEventListener('my_event', my_event_handler);

and I have the EventHandler where I want to remove some children from the stage:

private function my_event_handler(event:Event):void
{
     trace("my Event");
}

And nothing happens, can someone tell me what I am doing wrong?

Thanks


Solution

  • you need to assign the listener to the object that is dispatching it. From your code, it is unclear what is doing what - but, for example, in your Main:

    //class Main

    var _newClass:NewClass = new NewClass();
    _newClass.addEventListener("my_event"), handler);
    

    and then dispatch the event in NewClass

    //class NewClass
    this.dispatchEvent(new Event("my_event"));
    

    right now, you seem to be firing the event alright, but you are adding the listener to the wrong object (in this case, i think the Main class, which is not also doing the dispatching).

    Note - that if you dispatch the event in the constructor of NewClass, you will probably miss the event, as you'd be assigning the listener after the event has been fired. So fire it elsewhere.

    • update -

    As noted by @redconservatory, and @Prototypical, bubbling can be taken advantage of in this scenario. There are some limitations, however.

    Normally, if the use_capture parameter == false (the default) in the eventListener method sig, you do, indeed need to target an object directly to receive events. To enable the bubbling phase :

    this.addEventListener("my_event", handler, true); //use_capture == true
    

    The parent of the child that dispatches the event will now become an eligible target of the event, as it "bubbles" back up the hierarchy. And in this case @redconservatory's answer is correct. The important exception here is that bubbling is only available for DisplayObjects. NewClass must extend DisplayObject or an ancestor and be added to the display list for bubbling to function properly.

    from the liveDocs

    Capturing and bubbling happen as the Event object moves from node to node in the display list: parent-to-child for capturing and child-to-parent for bubbling. This process has nothing to do with the inheritance hierarchy. Only DisplayObject objects (visual objects such as containers and controls) can have a capturing phase and a bubbling phase in addition to the targeting phase.

    For a complete discussion of the very important topic of Event Propagation - check out this introduction to event handling.