分享

AS3与JS通讯

 bylele 2013-01-18

AS3与JS通讯【转】

在AS2中,实现AS2于JavaScript的通信可以借助于flashplayer8时期的api
AS2向JavaScript传递参数时使用
fscommand(参数1:字符串,参数2);
参数1是外部JavaScript的函数名,参数2是传递的变量参数
JavaScript向AS2传递参数,使用flash player的公用方法
例如:
window.document.myflash.SetVariable(参数1:字符串,参数2);
参数1是flash中的变量名,参数2是变量值
flashplayer的公用方法有很多,利用这些基本实现了JavaScript对flash的控制

而在AS3中,由于ActionScript的重写,很多类和方法发生了变化
原有的flashplayer的公用方法大多失效
取而代之的是更加严禁的代码实现方法
AS3与JavaScript或ActiveX等的通信借助于AS3的顶级类
public final class ExternalInterface来实现
这个类位于flash.external包中,可以直接使用
也可以在使用时先导入包,规范代码的样式
import flash.external

ExternalInterface类有三个公用静态属性和两个公用静态方法
属性:
available : Boolean
[static] [read-only] Indicates whether this player is in a container
that offers an external interface.

marshallExceptions : Boolean = false
[static] Indicates whether the external interface should attempt to
pass ActionScript exceptions to the current browser and JavaScript
exceptions to Flash Player.

objectID : String
[static] [read-only] Returns the id attribute of the object tag in
Internet Explorer, or the name attribute of the embed tag in Netscape.

方法:

addCallback(functionName:String, closure:Function):void
[static] Registers an ActionScript method as callable from the container.

call(functionName:String, ... arguments):*
[static] Calls a function exposed by the Flash Player container, passing zero
or more arguments.


其中addCallback方法是实现JavaScript向AS3中传递参数的
而call实现了flash向JavaScript中传递参数

先看call方法
call(functionName:String, ... arguments):*
call方法的返回值可以是任意类型的,第一个参数是字符串类型
使用的时候写要调用的JavaScript中的函数名,剩下的参数是传递给这个JavaScript
函数的参数,例如flash里要调用JavaScript里的myfun函数,并且传递给该函数
一个参数a,那么可以这样写
ExternalInterface.call("myfun",a);
如果有返回值,假设是字符串类型的,可以这样
var myreturn:String = ExternalInterface.call("myfun",a);
这样就是现了flash向外部JavaScript的通信

再看addCallback方法
addCallback(functionName:String, closure:Function):void
addCallback方法实现JavaScript向AS3传递参数
第一个变量是字符串类型,输入可以在外部(JavaScript或ActiveX中)使用的函数名
第二个参数是函数类型,是与外部可用的flash函数名相应的flash内部函数
举例说明:当使用了下面语句后
ExternalInterface.addCallback("jstoflashfun",flashfun);
那么此时flash便有了一个外部可以调用的方法 jstoflashfun()
而这个方法是在flash内部实现的,当外部调用jstoflashfun方法时
实际运行的是flash内部的flashfun函数
换句话说,addCallback方法实现了flash内部方法的外部声明
这里也可以写成
ExternalInterface.addCallback("flashfun",flashfun);
这样 flash内部方法就可以在外部调用了
我们看JavaScript传递变量的方法
在flash中的代码
ExternalInterface.addCallback("callFlash",callFlash);
function callFlash(test:String):void{
myvar=test;
}

在JavaScript的代码
<script language = "javascript">
function sendtoflash(val)
{
window.document.myflash.callFlash(val);//假设flash的id是myflash
}
</script>
当网页内发生sedtoflash调用事件时,就会调用flash的对外方法callFlash
从而将参数由JavaScript传递给flash
这样就实现了由JavaScript到flash的通信

上述只是实现了AS3与JavaScript之间最基本的通信
借助于强大的ExternalInterface类

    本站是提供个人知识管理的网络存储空间,所有内容均由用户发布,不代表本站观点。请注意甄别内容中的联系方式、诱导购买等信息,谨防诈骗。如发现有害或侵权内容,请点击一键举报。
    转藏 分享 献花(0

    0条评论

    发表

    请遵守用户 评论公约

    类似文章 更多