Mar 12

在前面的Flex中利用ExternalInterface的API调用JavaScript函数的例子中,我们了解到了Flex应用中,如何利用静态事件ExternalInterface.call()调用JavaScript函数。

接下来的例子展示了Flex应用中如何利用静态ExternalInterface.addCallback()事件和JavaScript中的比特(bit),调用ActionScript函数。

下面是具体的例子以及源代码:


Download: main.mxml
  1. <?xml version="1.0" encoding="utf-8"?>
  2. <!-- http://blog.flexexamples.com/2008/03/11/calling-actionscript-functions-from-your-html-templates-using-the-externalinterface-api/ -->
  3. <mx:Application xmlns:mx="http://www.adobe.com/2006/mxml"
  4.         layout="vertical"
  5.         verticalAlign="middle"
  6.         backgroundColor="white"
  7.         creationComplete="init();">
  8.  
  9.     <mx:Script>
  10.         <![CDATA[
  11.             import mx.controls.Alert;
  12.  
  13.             private var alert:Alert;
  14.  
  15.             private function init():void {
  16.                 ExternalInterface.addCallback("alert", showAlert);
  17.             }
  18.  
  19.             private function showAlert(msg:String):void {
  20.                 var now:Date = new Date();
  21.                 alert = Alert.show(msg,now.toLocaleDateString());
  22.                 alert.status = now.toLocaleTimeString();
  23.             }
  24.         ]]>
  25.     </mx:Script>
  26.  
  27. </mx:Application>

下面是JavaScript文件(/src/externalInterface.js):

  1. /** http://blog.flexexamples.com/2008/03/11/calling-actionscript-functions-from-your-html-templates-using-the-externalinterface-api/ */
  2. function thisMovie(movieName) {
  3.     if (navigator.appName.indexOf("Microsoft") != -1) {
  4.         return window[movieName];
  5.     } else {
  6.         return document[movieName];
  7.     }
  8. }
  9.  
  10. function asAlert(value) {
  11.     thisMovie("main").alert(value);
  12. }
下面是HTML模板需要添加的内容(/html-template/index.template.html):
  1. <head>
  2. . . .
  3. <script language="JavaScript" src="externalInterface.js"></script>
  4. </head>
  5. <body>
  6. . . .
  7. <div align=”center><h1>&lt;HTML /&gt;</h1></div>
  8. <div align=”center><input type="Button" value="Show Flex Alert" onClick="asAlert(’Hello World, from JavaScript’);" /></div>
  9. </body>

下面是执行实例(可以右键察看源代码):

原文作者:Peter deHaan 翻译:minidxer

written by Minidxer  |  tags: , , , , , , ,

Related Post

Leave a Reply