Friday, October 21, 2011

Closing PopUp on Esc Press

A nice to have feature that I was implementing, brought me to this. As it turns out, this actually is very easy to implement. Code below.

The Application File


<?xml version="1.0" encoding="utf-8"?>
<s:Application xmlns:fx="http://ns.adobe.com/mxml/2009"
  xmlns:s="library://ns.adobe.com/flex/spark"
  xmlns:mx="library://ns.adobe.com/flex/mx" minWidth="955" minHeight="600"
   >

<fx:Script>
<![CDATA[
import components.TestPopUp;

import mx.core.FlexGlobals;
import mx.managers.PopUpManager;

private function addPopUp(event:MouseEvent):void
{
var popup:TestPopUp = new TestPopUp();
PopUpManager.addPopUp(popup, FlexGlobals.topLevelApplication as DisplayObject, true);
PopUpManager.centerPopUp(popup);
}

]]>
</fx:Script>
<s:Button id="addPopBtn" label="Add Pop Up" click="{this.addPopUp(event)}"/>
</s:Application>

Custom Pop Up

<?xml version="1.0" encoding="utf-8"?>
<s:TitleWindow xmlns:fx="http://ns.adobe.com/mxml/2009" 
  xmlns:s="library://ns.adobe.com/flex/spark" 
  xmlns:mx="library://ns.adobe.com/flex/mx" 
  width="400" height="300" creationComplete="init()"
  close="onClose(event)">
<fx:Script>
<![CDATA[
import mx.events.CloseEvent;
import mx.managers.PopUpManager;
private function init():void
{
stage.addEventListener(KeyboardEvent.KEY_DOWN, onKeyDown);
}
private function onKeyDown(event:KeyboardEvent):void
{
if(event.keyCode == Keyboard.ESCAPE)
{
PopUpManager.removePopUp(this);
}
}
private function onClose(event:CloseEvent):void
{
PopUpManager.removePopUp(this);
}
]]>
</fx:Script>
<s:Label text="Hi There. Press Esc to close me."/>
</s:TitleWindow>

No comments :