瀏覽器關閉時, 如何提醒用戶保存Flex上的拓撲數據

 

有好多同學問當瀏覽器關閉時, Flex如何能得到通知, 提醒用戶保存數據. 這是個很普遍的問題, 下面就演示一下如何做.

Flex無法知道瀏覽器何時關閉, 但javascript可以(window.onbeforeunload), 所以思路就是:
1. Flex提供方法, 能讓javascript調用, 以便在瀏覽器關閉時, 判斷是否有數據需要保存, 如果有, 就提示, 沒有就啥都不幹<?xml version="1.0" encoding="utf-8"?>

<?xml version="1.0" encoding="utf-8"?>
<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml" layout="horizontal"
xmlns:tw="http://www.servasoftware.com/2009/twaver/flex"
creationComplete="init();" paddingBottom="0" paddingLeft="0" paddingRight="0" paddingTop="0">
<mx:Script>
<![CDATA[
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;
}
]]>
</mx:Script>
<mx:VBox ;100%" height="100%">
<mx:HBox ;100%">
<mx:Button id="btnSave" label="Save Location" click="save()" enabled="false"/>
</mx:HBox>
<tw:Network id="network" ;100%" height="100%"/>
</mx:VBox>
</mx:Application>

2. html頁面添加window.onbeforeunload事件, 判斷如果Flex有內容要保存, 就彈出提示:

<script>
window.onbeforeunload = function (evt) {
var demo = document.demo || window.demo;
if (demo.needSave()) {
var message = 'You did not save your data. Do you really want to quit?';
if (!evt) {
evt = window.event;
}
if (evt) {
evt.returnValue = message;
}
return message;
}
}
</script>

完整代碼見附件:TestWindowClose

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章