1. 程式人生 > >js呼叫flex中as方法

js呼叫flex中as方法

需要在mxml檔案中新增下面程式碼中的紅色部分:
mxml完整原始碼如下:

<?xml version="1.0" encoding="utf-8"?>
<s:Application xmlns:fx="http://ns.adobe.com/mxml/2009"
      xmlns:s="library://ns.adobe.com/flex/spark"
      xmlns:mx="library://ns.adobe.com/flex/mx" minWidth="955" minHeight="600"   initialize="application1_initializeHandler(event)">
 <fx:Script>
  <![CDATA[
   import mx.controls.Alert;
   import mx.events.FlexEvent;
   import flash.system.Security;
   
   Security.allowDomain("*");
   Security.allowInsecureDomain("*");

   protected function application1_initializeHandler(event:FlexEvent):void
   {
    // TODO Auto-generated method stub
    if(ExternalInterface.available)
    {
     ExternalInterface.addCallback("getFlexMsg",getMsgFromFlex);
    }
   }
   public function getMsgFromFlex():void
   {
    btnOK.label="js呼叫flex成功";
   }
   protected function button1_clickHandler(event:MouseEvent):void
   {
    // TODO Auto-generated method stub
    var msg:String=ExternalInterface.call("jsFun");
    mx.controls.Alert.show(msg);
   }
  ]]>
 </fx:Script>
 <fx:Declarations>
  <!-- 將非可視元素(例如服務、值物件)放在此處 -->
 </fx:Declarations>
 <s:Button id="btnOK" x="268" y="103" width="137" label="按鈕" click="button1_clickHandler(event)"/>
</s:Application>

JS呼叫程式碼如下:

function jsFun() //被flex中的as方法呼叫
  {
   return "來自js";
  }

  function getFlexMsg() //呼叫flex中的as方法
  {
   var msg=document.getElementById("JSandFlex").getFlexMsg(); //說明:JSandFlex是html檔案中flash builder生成的swf物件的id,getFlexMsg是在flex中註冊的可被js呼叫的as方法別名
  }

以上js程式碼可直接放在index.template.html的<head></head>內,也可放在單獨的檔案中然後在index.template.html中引用.