有好多同学问当浏览器关闭时, Flex如何能得到通知, 提醒用户保存数据. 这是个很普遍的问题, 下面就演示一下如何做.

浏览器关闭时, 如何提醒用户保存Flex上的拓扑数据_第1张图片

Flex无法知道浏览器何时关闭, 但javascript可以(window.onbeforeunload), 所以思路就是:
1. Flex提供方法, 能让javascript调用, 以便在浏览器关闭时, 判断是否有数据需要保存, 如果有, 就提示, 没有就啥都不干


xmlns:tw="http://www.servasoftware.com/2009/twaver/flex"
creationComplete="init();" paddingBottom="0" paddingLeft="0" paddingRight="0" paddingTop="0">

import mx.controls.Alert;
import twaver.*;
import twaver.network.interaction.InteractionEvent;
private var box:ElementBox = new ElementBox();
private function init():void {
this.initBox();
// Add callback, javascript use it to check whether popup message when browser is closing
ExternalInterface.addCallback("needSave", needSave);
// Enable save location button once location changed
network.addInteractionListener(function(e:InteractionEvent):void {
if(InteractionEvent.LAZY_MOVE_END == e.kind
|| InteractionEvent.LIVE_MOVE_END == e.kind) {
if(!btnSave.enabled){
btnSave.enabled = true;
}
}
});
}
private function initBox():void {
var from:Node = new Node();
from.name = "From";
from.location = new Point(100, 200);
box.add(from);
var to:Node = new Node();
to.name = "To";
to.location = new Point(400, 500);
box.add(to);
box.add(new Link(from, to));
this.network.elementBox = box;
}
private function save():void {
saveData();
btnSave.enabled = false;
}
private function saveData():void {
Alert.show("Data saved");
}
public function needSave():Boolean {
return btnSave.enabled;
}
]]>







2. html页面添加window.onbeforeunload事件, 判断如果Flex有内容要保存, 就弹出提示:

完整代码见附件:TestWindowClose