Wednesday, July 23rd, 2008
Getting to know GWT JSNI; Including talking to GWT code from JavaScript
<p>Bruce Johnson has written an expansive post on understanding the GWT JavaScript Native Interface (JSNI). It starts out with the piece that some people know about, namely inlining native JavaScript such as this:But what about calling back out to Java from within native land?
-
-
package org.example.foo;
-
public class Flipper {
-
var re = /(w+)s(w+)/;
-
var s = name.replace(re, '$2, $1');
-
this.@org.example.foo.Flipper::onFlip(Ljava/lang/String;)(s);
-
}-*/;
-
-
// do something useful with the flipped name
-
}
-
}
-
You can also access any JavaScript, loaded from a script source or however via:
-
-
// A Java method using JSNI
-
$wnd.sayHello(name); // $wnd is a JSNI synonym for 'window'
-
}-*/;
-
But finally, what about if you wrote a bunch of Java code for GWT, and you want JavaScript to call that? Simply link the code back through the $wnd world:
-
-
package org.example.yourcode.format.client;
-
public class DateFormatterLib implements EntryPoint {
-
-
// Expose the following method into JavaScript.
-
}
-
-
// Set up the JS-callable signature as a global JS function.
-
private native void publish() /*-{
-
$wnd.formatAsCurrency =
-
@org.example.yourcode.format.client.DateFormatterLib::formatAsCurrency(D);
-
}-*/;
-
-
// Auto-publish the method into JS when the GWT module loads.
-
public void onModuleLoad() {
-
publish();
-
}
-
}
-
For more, check out this talk on the topic given by the GWT architect Scott Blum:
Related Content:











Leave a comment