Mar 12
在前面的Flex中利用ExternalInterface的API调用JavaScript函数的例子中,我们了解到了Flex应用中,如何利用静态事件ExternalInterface.call()调用JavaScript函数。
接下来的例子展示了Flex应用中如何利用静态ExternalInterface.addCallback()事件和JavaScript中的比特(bit),调用ActionScript函数。
下面是具体的例子以及源代码:
Download: main.mxml
- <?xml version="1.0" encoding="utf-8"?>
- <!-- http://blog.flexexamples.com/2008/03/11/calling-actionscript-functions-from-your-html-templates-using-the-externalinterface-api/ -->
- <mx:Application xmlns:mx="http://www.adobe.com/2006/mxml"
- layout="vertical"
- verticalAlign="middle"
- backgroundColor="white"
- creationComplete="init();">
- <mx:Script>
- <![CDATA[
- import mx.controls.Alert;
- private var alert:Alert;
- private function init():void {
- ExternalInterface.addCallback("alert", showAlert);
- }
- private function showAlert(msg:String):void {
- var now:Date = new Date();
- alert = Alert.show(msg,now.toLocaleDateString());
- alert.status = now.toLocaleTimeString();
- }
- ]]>
- </mx:Script>
- </mx:Application>
下面是JavaScript文件(/src/externalInterface.js):
Download: externalInterface.js
- /** http://blog.flexexamples.com/2008/03/11/calling-actionscript-functions-from-your-html-templates-using-the-externalinterface-api/ */
- function thisMovie(movieName) {
- if (navigator.appName.indexOf("Microsoft") != -1) {
- return window[movieName];
- } else {
- return document[movieName];
- }
- }
- function asAlert(value) {
- thisMovie("main").alert(value);
- }
下面是HTML模板需要添加的内容(/html-template/index.template.html):
Download: index.template.html
- <head>
- . . .
- <script language="JavaScript" src="externalInterface.js"></script>
- </head>
- <body>
- . . .
- <div align=”center”><h1><HTML /></h1></div>
- <div align=”center”><input type="Button" value="Show Flex Alert" onClick="asAlert(’Hello World, from JavaScript’);" /></div>
- </body>
下面是执行实例(可以右键察看源代码):
原文作者:Peter deHaan 翻译:minidxer
