问题

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!
回答1:
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
}
回答2:
First of all you need to learn how to declare custom events and handle them. You have a simple guide here from Adobe : http://cookbooks.adobe.com/post_AS3__Creating_and_dispatching_Custom_Events-17609.html
You may also want to read about how events bubble and are captured in the following link: http://help.adobe.com/en_US/as3/mobile/WS948100b6829bd5a67edfb831266c0b5fc6-8000.html
Now let's go through the cases you ask:
Case 1. From Child 1 to Child 2: In essence unless Child 2 listens to an event of child 1 it will not be able to capture it since they do not have a parental kind of relationship. What you can do is the following: Declare an event in Child 1 and listen and capture it from the container. The container can call a method in Child 2 as a result of the event being triggered from Child 1.
Case 2. From Child 1 to Child 3: It is basically the same as Child 1 to Child 3, only that when the container calls the Child 2, the Child 2 calls the Child 3 as well.
Case 3. Child 3 to Child 1. Child 3 can raise an event which can bubble up all the way to the Container. The container can then call the desired method in Child 1.
Hope that helped.
来源:https://stackoverflow.com/questions/16264885/as3-can-i-dispatch-event-from-one-child-to-another