Wednesday, May 5, 2010

Flash asynchronous alert and pause application problems solved

Single threaded architecture of flex poses a rather irritating problem with Alert dialog box poses, especially when the next step involves a confirmation from the user. I have written a SynchronousAlert class in actionscript 3.0 that basically relies on ExternalInterface to make the alert through javascript, this way the app is suspended till the external function call return. Plz note that i have used javascript alert just for demonstration here, If you need something fancier the code can easily be modified to actually make another dummy flash app to do the alert or a custom html popup alert can be shown.

Similarly to pause the application one coould just use the javascript's settimeout function rather than inside the flash
Find below the code for the synchronousAlert wrapper class

package components
{
import flash.display.Sprite;
import flash.external.ExternalInterface;
import flash.utils.setTimeout;

import mx.controls.Alert;
import mx.core.FlexGlobals;
import mx.core.IFlexModuleFactory;
import mx.events.CloseEvent;

public class SynchronousAlert
{
private var semapore:Boolean=false;
private var s:String=null;
public function SynchronousAlert()
{

}
public function show(text:String = "",
yesno:Boolean= false):uint
{
if(yesno) callConfirm(text);
else callAlert(text);
while(!semapore)
{
trace("Waiting");
}

if(s==null) return Alert.OK;
if(s=="true") return Alert.YES;
else return Alert.NO;
}

public function callAlert(text:String):void {
var s:String;
if (ExternalInterface.available) {
var wrapperFunction:String = "alert";
s = ExternalInterface.call(wrapperFunction, text );
s="false";
} else {
s = "Wrapper not available";
}

semapore=true;
}
public function callConfirm(text:String):void {
if (ExternalInterface.available) {
var wrapperFunction:String = "confirm";
s = ExternalInterface.call(wrapperFunction, text);
} else {
s = null;
}
semapore=true;
}

}
}


A example use of the above class could be

if((new SynchronousAlert).show("Are you sure you want to reset the scores",true)==Alert.YES) return true; else return false;


Feel free to use the above code with or without any credits

2 comments:

Rick Reumann said...

Thanks for posting this. I'm going to give it a try. I can't believe Flex doesn't have a synchronous confirmation dialog.

Arvind said...

Actually flash is single threaded, hence can't pause the execution , without making the application non responsive to use keyboard,mouse etc