as與js相互通信(flex中調用js函數)

Flex中As調用Js的方法是:
     1、導入包 (import flash.external.ExternalInterface;)
     2、使用ExternalInterface.call("Js函數名稱",參數)進行調用,其返回的值就是Js函數所返回的值

Js調用As的方法是:
     1、導入包 (import flash.external.ExternalInterface;)
     2、在initApp中使用ExternalInterface.addCallback("用於Js調用的函數名",As中的函數名)進行註冊下
     3、js中 就可以用document.getElementById("Flas在Html中的ID").註冊時設置的函數名(參數)進行調用


as和js通信addcallback失效
參考原文:http://www.zhaohongri.cn/?p=14

情況一:flash一旦在瀏覽器裏cache住,如果在as裏一開始就addcallback就會失效
情況二:一個js函數上來就調用as的一個函數的時候,頁面會報錯,提示找不到這個flash對象,或者函數沒有定義。Flash8的時代,針對 ExternalInterface這個類,文檔裏只說明了怎麼用,而沒有具體說怎麼合理的組織和頁面的結構,一直到了cs3的時代,幫助裏才說明了正確的函數註冊和js調用的過程,具體的見Flash cs3幫助。大概的代碼如下:

js部分:

           <script>
var jsReady=false;
var swfReady=false;

function isReady(){
return jsReady;
}

function setSwfIsReady(){
      swfReady=true;
   getSWF(”flashobj”).fun()

}

function pageInit(){
     jsReady=true;
}

function getSWF(movieName) {
   if (navigator.appName.indexOf(”Microsoft”) != -1) {
    return window[movieName+”_ob”];
   } else {
    return document[movieName+”_em”];
   }
}

οnlοad=function(){
   pageInit();
}

</script>

注意,在getSWF函數裏用了 return window[movieName+”_ob”]和return document[movieName+”_em”],在IE下,如果object標籤和embed表現用同樣的id,通過js去訪問flash對象的時候,IE會認不出,FF是沒有問題的

as部分

private function registerJsFun():void{
       if(ExternalInterface.available){
     try{
      var containerReady:Boolean=isContainerReady();
      //ExternalInterface.call(”ceshi”,”registerJsFun:”+containerReady);
      if(containerReady){
       //註冊函數
       setupCallBacks();
      }else{
       //檢測是否準備好
       var readyTimer:Timer=new Timer(100);
       readyTimer.addEventListener(TimerEvent.TIMER,timeHandler);
       readyTimer.start();
      }
     }catch(error:Error){
      trace(error)
     }
    }else{
     trace(”External interface is not available for this container.”);
    }
   }
 
private function timeHandler(event:TimerEvent):void{
var isReady:Boolean=isContainerReady();
      if(isReady){
   Timer(event.target).stop();
   setupCallBacks();
}
}

private function isContainerReady():Boolean{
var result:Boolean=Boolean(ExternalInterface.call(”isReady”));
return result;
}

private function setupCallBacks():void{
       ExternalInterface.addCallback(”fun”,fun);

        ExternalInterface.call(”setSwfIsReady”);
     }

具體我就不解釋了,不明白的可以仔細去看下cs3幫助,大概的意思就是頁面開始渲染的時候js去調用swf對象,有可能swf對象沒有完全 load完,所以這個觸發器要從flash開始,當flash加載的時候就開始不停的調用頁面的一個函數,取一個頁面是否加載完畢的標識,當 pageonLoad後,這個標識爲true了,說明flash也加載完畢了,這個時候flash再開始註冊函數,同時調用頁面的js,讓js調用 Flash對象

 


實例:a.mxml


<?xml version="1.0" encoding="utf-8"?>
<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml" layout="absolute">
    <mx:Script>
        <![CDATA[ 
      import flash.external.*;
      public function asFunc():String {
          return sending_ti.text;
      }
     
      public function initApp():void {
        //AddCallback方法允許javascript調用flash時間上函數
          ExternalInterface.addCallback("flexFunctionAlias", asFunc);
      }
     
         public function callWrapper():void {     
             var f:String = "changeDocumentTitle";
       //ExternalInterface.call(functionName:String,Parameters)可以調用javascript函數
       //參數1: functionName – 你想要調用的javascript函數名要以字符串的形式
       //參數2: Parameters – 需要傳遞給javascript函數的參數,用逗號分開,是可選的。             
             var getJSValue:String = ExternalInterface.call(f,"New Title");
             received_ti.text = getJSValue;
        }

        ]]>
    </mx:Script>
    <mx:Button id="send_button" x="368" y="100" click="initApp();" label="發送" fontSize="12" width="62"/>
    <mx:TextInput id="received_ti" x="148" y="62" width="203" fontSize="12"/>
    <mx:TextInput id="sending_ti" x="148" y="100" width="203" fontSize="12"/>
    <mx:Label x="105" y="65" text="收到" fontSize="12"/>
    <mx:Label x="105" y="103" text="發送" fontSize="12"/>
    <mx:Button x="368" y="64" click="callWrapper();" label="接收" fontSize="12" width="62"/>
</mx:Application>


index.html

<!DOCTYPE HTML PUBLIC "-//W3C//Dtd nowrap HTML 4.01 Transitional//EN">
<html>
<head>
  <base target="_self">
  <title></title>
  <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
  <meta http-equiv="pragma" content="no-cache">
  <meta http-equiv="cache-control" content="no-cache">
  <meta http-equiv="expires" content="0">
</head>

<script language="JavaScript">
    function callApp() {
        var x = MyFlexApp.flexFunctionAlias();
        document.getElementById('receivedField').value = x;
    }

    function changeDocumentTitle(a) {
        window.document.title=a;
        return document.getElementById('sendField').value;
    }
</script>

<body style='overflow-x:hidden;overflow-y:hidden'>
  <form name="htmlForm">
     數據發送給AS:
    <input type="text" id="sendField" />
    <input type="button" value="發送" οnclick="" /><br />
    <br />
    接收AS的數據:
    <input type="text" id="receivedField">
    <input type="button" value="接收" οnclick="callApp();" /><br />   
  </form>
   <OBJECT id="MyFlexApp" classid="clsid:D27CDB6E-AE6D-11cf-96B8-444553540000"codebase="http://download.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=6,0,0,0" WIDTH="100%" HEIGHT="500">
      <PARAM NAME=movie VALUE="joinJS.swf">
      <PARAM NAME=quality VALUE=high>
      <PARAM NAME=scale VALUE=noborder>
      <PARAM NAME=bgcolor VALUE=#000000>
      <EMBED src="joinJS.swf" quality=high WIDTH="100%" HEIGHT="500" scale=noborder bgcolor=#000000 NAME="TH2"TYPE="application/x-shockwave-flash" PLUGINSPAGE="http://www.macromedia.com/go/getflashplayer"></EMBED>
   </OBJECT>
</body>

本文來自CSDN博客,轉載請標明出處:http://blog.csdn.net/hartkevin/archive/2010/03/10/5361524.aspx

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