Sunday, June 7, 2009

Object Reference and Method Call in JavaScript with GWT JSNI

There are times we need to call JavaScript functions from the hosted page in GWT that would use the runtime objects of the GWT compiled code. Put it in another way, there are situations the in the middle of the JavaScript, you may need the real object from GWT code. This means that we cannot use the native static methods in JSNI. Thanks to JavaScript, there could be a solution to this:
1- Define a JavaScript variable that would actually hold a reference to a function. And, define a JavaScript function that would set this reference (This code is written in your index.html GWT page):
var functionReference;

function setFunctionReference(fr) {
     functionReference = fr;
}



2- Use GWT JSNI (JavaScript Native API) to set the object reference for the function:
public class MyEntryPoint implements EntryPoint{

public void onModuleLoad() {

// BLAH BLAH CODE

setFunctionReferenceForMe(this);

// BLAH BLAH CODE
}

public native void setFunctionReferenceForMe(MyEntryPoint ep)/*- {
   $wnd.setFunctionReference(funtion(param) {
      if (param == 0) {
         ep.@com.myworld.edu.gwt.client.MyEntryPoint
         ::method1();
      } else {
         ep.@com.myworld.edu.gwt.client.MyEntryPoint
         ::method2(Ljava/lang/String;)(param);
      }
    });
}-*/;

public void method1() {
// A non-static method called from JavaScript
}

public void method2(String param) {
// A non-static method called from JavaScript
}

}

Through this piece of code, you see that we can actually call a non-static method of an object in GWT using a trick with JSNI and some JavaScript in hosted page. Alongside, we are actually passing parameter from JavaScrip to that object, too. So, now we can call the method wherever we want through JavaScript:
functionReference.call(this, 0)
And, sure it knows about the object reference from GWT.