nitin
nitin

Reputation: 75

How to listen to events inside the child component dispatched by the parent component

When an event is dispatched by a component, there are three phases in which the event flows, capture - event flows from the application to the component which dispatches the event, target when the event is at the Target which actually dispatches the event , then the bubbling phase in which the event flows from the target to the application. There is a situation in which Application has child comp1 , comp1 has child comp2. I have a button in the comp1 which dispatches the event and I want to listen to that event inside the comp2. Ideally the event would flow from Application->comp1->button->comp1->Application. How can I achieve my objective?

Upvotes: 0

Views: 2350

Answers (2)

Amy Blankenship
Amy Blankenship

Reputation: 6961

What you're suggesting is probably not the best way to go about it. You should probably handle this better by having the parent explicitly do something that helps the child know what to do.

One way to do this is to use the concept of an event bus, such as what you see in RobotLegs. Just give your child2 a public field or property called eventBus with a type of IEventDispatcher. You can then have the parent populate this property with this. I usually set such properties up as getters/setters, so that the property can be nulled when the child is removed from the stage and the child can remove its listeners.

This lets you start with exactly what you need to make this happen, but if you discover yourself using child2 in a situation where you need it to listen to a different object, you're ready to go.

A second possibility is to just expose a method on the child that the parent can call (the parent already has a reference to the child--you're not introducing unnecessary coupling here), and simply call it instead of dispatching the event.

Upvotes: 0

RIAstar
RIAstar

Reputation: 11912

Inside comp1 dispatch your event and make sure it bubbles:

myButton.addEventListener(MouseEvent.CLICK, handleMyButtonClick);

private function handleMyButtonClick(event:MouseEvent):void {
     dispatchEvent(new Event("myCustomEvent", true));
}

Now inside comp2 listen for this event on the stage:

stage.addEventListener("myCustomEvent", handleMyCustomEvent);

That's it: because the event bubbles, it will always at some point hit the stage. So you can use it to listen from anywhere. Just don't forget to make sure the stage property of comp2 is set before you try to attach a listener.

Note: be aware that all components in your application will be able to see this event, so make sure that the right component handles the right event. For starters I would never use this approach with built-in events; only use custom events whose types do not coincide with the built-in ones.

Upvotes: 1

Related Questions