I have a Flex client application. I need a clean up function to run in Flex when the user closes the browser. I found the following solution on the net, but it only works half-way for me. How could I fix it? Thanks in advance for any responses!
Symptoms
CustomEvent
triggered, but not executed.
>> EventHandler forCustomEvent.SEND_EVENTS
is defined by a Mate EventMap. All the handler does is to call anHTTPServiceInvoker
. In debug console, I'm able to see the handler and HTTPServiceInvoker being triggered, but neither theresultHandlers
nor thefaultHandlers
were called. I know this event handler has no problem because when I dispatch the sameCustomEvent.SEND_EVENTS
in a button click handler, it behaves exactly as I expected)- Browser seems to wait for cleanUp function to complete before it closes. (all traces were printed before browser closes down)
Code
I added the following into the index.template.html
window.onbeforeunload = clean_up;
function clean_up()
{
var flex = document.${application} || window.${application};
flex.cleanUp();
}
And used the following in the application MXML file
import flash.external.ExternalInterface;
public function init():void {
ExternalInterface.addCallback("cleanUp",cleanUp);
}
public function cleanUp():void {
var newEvent:CustomEvent = new CustomEvent(CustomEvent.SEND_EVENTS);
newEvent.requestObj = myFormModel;
dispatchEvent(newEvent);
// for testing purposes
// to see whether the browser waits for Flex cleanup to finish before closing down
var i:int;
for (i=0; i<10000; i++){
trace(i);
}
}
My Setup
- FlexBuilder 3
- Mate MVC Framework (Mate_08_9.swc)
- FlashPlayer 10
Unfortunately, there is no solid way of doing such clean up functions that execute asynchronously. The
result
/fault
events of the HTTPService occur asynchronously after thecleanUp
method is returned. The browser waits only till theonbeforeunload
function (the js clean_up function) returns. Unless you callevent.preventDefault()
from that function, the page will be closed. Note that calling preventDefault() will result in an ok/cancel popup asking:If the user selects OK, the browser will be closed nevertheless. You can use the
event.returnValue
property to add a custom message to the popop.