小小菜鸟的web菜园子

web开发学习。好记性不如烂笔头。每天进步一点点!

导航

在flash/flex程序中处理javascript的事件

To get started you will need to download the library JSInterface from http://code.google.com/p/jsinterface/

Then, create a project and add(Properties -> ActionScript Build Path -> Library path -> Add SWC...) the library to the project. It is necessary to initialize JSInterface, prior to use. To do so you need call the method JSInterface.initialize(). This method as the first argument accepts any object which can tell URL from which loaded this flash/flex program.

The value of this argument can be:

<!--[if !supportLists]-->·         <!--[endif]-->Any DisplayObject added to the stage

      JSInterface.initialize(this.stage);

 

<!--[if !supportLists]-->·         <!--[endif]-->LoaderInfo object of the current program

      JSInterface.initialize(this.loaderInfo);

 

<!--[if !supportLists]-->·         <!--[endif]-->String URL

            var url:String = "http://someserver.com/main.swf";

      JSInterface.initialize(url);

This argument is required if HTML page do not specify ID for this SWF.

The last thing you need to do is create a function and assign it a specific JavaScript object as a parameter. To access the JavaScript object you need to use class JSInterface and top level DOM object from the root structure of HTML page.

<!--[if !supportLists]-->·         <!--[endif]-->JSInterface.window - JavaScript window object

<!--[if !supportLists]-->·         <!--[endif]-->JSInterface.document - JavaScript document object

<!--[if !supportLists]-->·         <!--[endif]-->JSInterface.navigator - JavaScript navigator object

<!--[if !supportLists]-->·         <!--[endif]-->JSInterface.main - JavaScript HTMLElement object which contain currect instance of flash player

For example, I assign a function to handle event click HTML document:

package {

      import aw.external.JSInterface;

     

      import flash.display.Sprite;

     

      [SWF(width="20", height="20")]

      public class Test extends Sprite{

            public function Test():void{

                  super();

                  JSInterface.initialize(this);

                  JSInterface.document.body.onclick = this.onclickHandler;

            }

            protected function onclickHandler():void{

                  trace(' TEST ');

            }

      }

}

This example can not work locally, if so - start debug session over HTTP.

You can change this example to handle click event from HTML button.

Add button to default HTML template:

      <input type="button" id="clickButton" value="Click me!"/>

Change JSInterface object using buttons ID:

      JSInterface.document.getElementById('clickButton').onclick = this.onclickHandler;

Happy clicking!

posted on 2009-02-16 11:55  『小小菜鸟』  阅读(909)  评论(1编辑  收藏  举报