简体   繁体   中英

Referencing problem when adding callbacks to Exernal Interface in Flash/ActionScript3

I have a method: myMethod() {} that I want to make accessible to javascript. I've done a bit of research and found out you need to add a callback to ExernalInterface, so here's what I have done:

ExternalInterface.addCallback("invokeMyMethod", myMethod);

Now when I load up my web page with the flash on it, I get an error:

ReferenceError: Error #1065: Variable myMethod is not defined. at Main$cinit() at global$init()

myMethod is contained within the Main class... here is how Main.as looks:

package {
   import flash.external.ExternalInterface;
   import flash.events.Event;
   //import a bunch of other things...

   if( ExternalInterface.available ) {
      ExternalInterface.addCallback("invokeMyMethod", myMethod);
   }

   public class Main extends Sprite {
      //A bunch of other methods...

      public function myMethod(str:String):void { 
         //Do something here
      }
   }
}

I have no clue how to make ExernalInterface.addCallback realize that myMethod exists... Anyone have any ideas?

Thanks,
Matt

Your myMethod function is inside of the Main class, but your reference to it (in the if statement) is not. If you make myMethod static, then your addCallback statement could look like this:

ExternalInterface.addCallback("invokeMyMethod", Main.myMethod);

Or if you have an instance of Main somewhere, you could write:

ExternalInterface.addCallback("invokeMyMethod", myObj.myMethod);

Jacob's answer above works just fine. But it created other errors because it was now trying to access non-static variables from a static method... So I tried this:

I moved the:

   if( ExternalInterface.available ) {
      ExternalInterface.addCallback("invokeMyMethod", myMethod);
   }

into my Main class, like this:

package {
   import flash.external.ExternalInterface;
   import flash.events.Event;
   //import a bunch of other things...     

   public class Main extends Sprite {
      //A bunch of other methods...

      if( ExternalInterface.available ) {
         ExternalInterface.addCallback("invokeMyMethod", myMethod);
      }

      public function myMethod(str:String):void { 
         //Do something here
      }
   }
}

And it worked fine

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM