2007-06-08

AS3 和 AS2 溝通

Adobe CS3 才上市不久, 大部份的人對 Flash CS3 不是頂熟稔
若要使用 ActionScript 3 的新功能, 卻又想以熟悉的 Flash 8 開發
遇到的最大問題就是 ActionScrip 3 和 ActionScript 2 的溝通
目前常用的作法有兩種: LocalConnection 和 ExternalInterface

在使用 SWF 9 (from Flex 2) 載入 SWF 8 (from Flash 8) 的情況下, 使用文字資料做測試
LocalConnection 每次只能傳送低於 40K 的資料
透過 ExternalInterface 則可以傳遞超過 1M 的資料給 JavaScript

LocalConnection 明顯只適用於傳遞少量資料
缺點: 接收的 SWF 實體只能有一個 (第二個實體之後是收不到資料的)
優點: 不限實體的執行形式 (EXE, flash player, flash plugin)
ExternalInterface 的缺點是必須要有 plugin container 當中介的角色

之前遇到的一個情況是 SWF9 載入兩支 SWF8 (a 和 b)
● SWF8a 負責和使用者互動, 讓使用者編輯
● SWF8b 負責產生上傳的圖片
● SWF9 負責將 SWF8b 的內容上傳
SWF8a 透過 EI 傳遞 XML 給 SWF8b 產生圖片
SWF8b 完成圖片後, 透過 EI 叫 SWF9 上傳圖片

SWF8a: AS2
import flash.external.ExternalInterface;
ExternalInterface.call("toRender", _xml.toString());

JavaScript:
function toRender(str){
if(navigator.appName.indexOf("Microsoft") != -1){
window.room_planner.renderPic(str);
}else{
window.document.room_planner.renderPic(str);
}
return true;
}
function uploadImage(){
if(navigator.appName.indexOf("Microsoft") != -1){
window.room_planner.uploadImage();
}else{
window.document.room_planner.uploadImage();
}
return true;
}

SWF8b: AS2
import flash.external.ExternalInterface;
var successRegist = ExternalInterface.addCallback("renderPic", null, render);
//
function render(d_str) {
// loading objects ...
onEnterFrame = sdEnterFrame;
}
function sdEnterFrame() {
var all_loaded = true;
for (var i = 0; i < loadee_ar.length; i++) {
if (loadee_ar[i].c_mc.getBytesLoaded() < 10) {
all_loaded = false;
break;
}
}
if (all_loaded) {
resizeToUpload();
ExternalInterface.call('uploadImage');
delete this.onEnterFrame;
}
}

SWF9: AS3
private function init():void{
// ...
ExternalInterface.addCallback('uploadImage', uploadImage);
}
private function uploadImage():void{
pop = PopUpManager.createPopUp(this, MyMsgWin, true);
pop.x = 440;
pop.y = 296;

var timer:Timer = new Timer(500, 1);
timer.addEventListener(TimerEvent.TIMER_COMPLETE, doUploadImage);
timer.start();
}

沒有留言:

FB 留言