Avg. Rating 5.0

Problem

I'm using the PopUpManager to display popups in my application. I want the popup to be closed when the user click on the modal (the semi-transparent component "behind" the popup).

Solution

We'll use the "mouseDownOutside" FlexEvent, which is dispatched when the user is click outside the target. As the modal blocks the whole UI, if the user has clicked outside, he has clicked on the modal

Detailed explanation

My popup

Here is a simple MXML component containing a BitmapImage
<?xml version="1.0" encoding="utf-8"?>
<s:Group xmlns:fx="http://ns.adobe.com/mxml/2009" xmlns:s="library://ns.adobe.com/flex/spark" xmlns:mx="library://ns.adobe.com/flex/halo" width="400" height="300">
    <s:layout>
        <s:BasicLayout/>
    </s:layout>
    <s:BitmapImage source="@Embed('../../../assets/logo.jpg')" />
</s:Group>

My application

package com.palleas.components
{
    import mx.events.FlexEvent;
    import mx.events.FlexMouseEvent;
    import mx.managers.PopUpManager;
   
    import spark.components.Application;
   
    public class Facade extends Application
    {
        public function Facade()
        {
          super();
          addEventListener(FlexEvent.CREATION_COMPLETE,creationCompleteHandler);
        }
       
        /**
         * This method is called when the component is ready
         * @param e
         *
         */       
        protected function creationCompleteHandler(e:FlexEvent):void
        {
          // we don't need this anymore
          removeEventListener(FlexEvent.CREATION_COMPLETE,creationCompleteHandler);
          // creating the modal pop-up
          var popup:PrettyPopup = PopUpManager.createPopUp(this,PrettyPopup,true) as PrettyPopup;
          // centering the created pop-up
          PopUpManager.centerPopUp(popup);
          // adding a listening on the click-outside event
          popup.addEventListener(FlexMouseEvent.MOUSE_DOWN_OUTSIDE,modalClickHandler);
        }
       
        /**
         * This method is called the user has clicked "outside" the popup
         * which mean on the modal
         * @param e
         *
         */       
        protected function modalClickHandler(e:FlexMouseEvent):void
        {
          // getting the targeted popup
          var popup:PrettyPopup = PrettyPopup(e.target);
          // removing the listener
          popup.removeEventListener(FlexMouseEvent.MOUSE_DOWN_OUTSIDE,modalClickHandler);
          // destroying the popup
          PopUpManager.removePopUp(popup);
        }
    }
}

Conclusion

We could have used a simple "click" event, and test the target property, but this method is really more logical.

Report abuse

Related recipes