views:

307

answers:

2

Hi,

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

A: 

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
Is there any other way to do it other than making it static? I've tried putting: ExternalInterface.addCallback("invokeMyMethod", Main.myMethod); in the Main class and I still get the same reference error... I can't think of what else to do.
Matt
btw static did get rid of that error, but it created other ones, that's why i'd like to avoid making it static if I can
Matt
A: 

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

Matt