Friday, March 26, 2010

Dispatching Events from Popups in FLEX

Sometimes we don't know (or forget) some silly things. Today I required to dispatch an custom event from a popup and handle that in component (parent mxml) in/on which that popup was opened. I normally used this line in popup:

this.dispatchEvent(new Event("myEvent"));

and handled this in the parent(of popup) mxml as:

this.addEventListener("myEvent",myEventHandler);

private function myEventHandler(event:Event):void
{
Alert.show("I came here");
}

While looking everything is fine but the (intended) functionality didn't worked.
i.e the event was fired but the Alert(event handler) was not executed.

I spend some 1 hour on this thinking any typo error is there.

Then I opened GOOGLE mahatma and searched for this
(I scolded myself why I didn't done this at first itself)

The first two results itself told all the story.

The first link said:
"DisplayObjects created through the PopupManager.createPopup() function are not children of the application container"
i.e popups are not children of Application container so the 'event' dispatched in popup can't be handled in its parent.

http://www.munkiihouse.com/?p=45

The second link gave me the solution:

Add the listener to popup while creating it in parent(mxml).

var myPopupObj:MyPopUp = PopUpManager.createPopUp(this,MyPopUp);
myPopupObj.addEventListener("myEvent",myEventHandler);
//This is where everything lies. Assign eventlistner for popup

Now dispatch the event(myEvent) as usually from the popup and it will be handled in its parent mxml(myEventHandler);

http://matthijs.stichelz.be/blog/2008/12/dispatch-custom-events-from-popup/

May this is an small thing but its useful.

1 comment:

  1. Hi Body, thanks a lot for this.
    I try find in google and find anything.

    I read this and....
    THANKSSSSS ¡¡¡¡
    salve my life

    ReplyDelete