Search code examples
javascriptflashactionscript-3externalinterfaceaddcallback

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


Solution

  • 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