Search code examples
actionscript-3eventsdispatcherchildren

AS3: Can I dispatch Event from one Child to another?


enter image description here

Hi guys, I cannot sort out this enigma :).

How to send dispatchEvent from Child1 and catch this event in Child2?

or

How to send dispatchEvent from Child1 and catch this event in Child3?

or

How to send dispatchEvent from Child3 and catch this event in Child1?

Thanks guys. I will appreciate some help here!


Solution

  • Although I get what you are trying to achieve, I think the better design approach is to allow the container to manage it's children.

    For example if container receives an event from child1, it's container's role to take care of notifying the other children if appropriate. This approach also makes it very clear in the container code the basic interaction between all the container's children. If I were going over someone's code, I'd appreciate such methodology for that reason.

    That being said, you could have a method in child2 and child3 that would allow you to pass child1 as a parameter, and then add a listener for child1 within. For example :

    in container code :

    child2.setChildListener(child1);
    child3.setChildListener(child1);
    

    Then in child2 and child3 , you could do something like this :

    public function setChildListener(childToListenTo:MovieClip):void
    {
        childToListenTo.addEventListener(MouseEvent.CLICK, childClickedHandler);
    }
    
    private function childClickedHandler(e:MouseEvent):void
    {
        // react to the child click here
    }