Flex中利用ExternalInterface API从HTML模板(HTML templates)中调用ActionScript函数的例子

在前面的 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.     <mx:Script>
  9.         <![CDATA[
  10.             import mx.controls.Alert;
  11.             private var alert:Alert;
  12.             private function init():void {
  13.                 ExternalInterface.addCallback("alert", showAlert);
  14.             }
  15.             private function showAlert(msg:String):void {
  16.                 var now:Date = new Date();
  17.                 alert = Alert.show(msg,now.toLocaleDateString());
  18.                 alert.status = now.toLocaleTimeString();
  19.             }
  20.         ]]>
  21.     </mx:Script>
  22. </mx:Application>
下面是JavaScript文件(/src/externalInterface.js):
Download: 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. function asAlert(value) {
  10.     thisMovie("main").alert(value);
  11. }
下面是HTML模板需要添加的内容(/html-template/index.template.html):
Download: 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>

你可能感兴趣的:(职场,休闲,API从HTML模板(HTML)