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

十年热恋 提交于 2019-12-11 06:44:34

问题


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

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