RSS

GWT JSNI: Talking to GWT code from JavaScript

28 Sep
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:

PLAIN TEXT

JAVA:

  1. // Java method declaration…
  2. native String flipName(String name) /*-{
  3. // …implemented with JavaScript
  4. var re = /(\w+)\s(\w+)/;
  5. return name.replace(re, ‘$2, $1’);
  6. }-*/;

But what about calling back out to Java from within native land?

JAVA:

  1. package org.example.foo;
  2. public class Flipper {
  3. public native void flipName(String name) /*-{
  4. var re = /(\w+)\s(\w+)/;
  5. var s = name.replace(re, ‘$2, $1’);
  6. this.@org.example.foo.Flipper::onFlip(Ljava/lang/String;)(s);
  7. }-*/;
  8. private void onFlip(String flippedName) {
  9. // do something useful with the flipped name
  10. }
  11. }

You can also access any JavaScript, loaded from a script source or however via:

JAVA:

  1. // A Java method using JSNI
  2. native void sayHelloInJava(String name) /*-{
  3. $wnd.sayHello(name); // $wnd is a JSNI synonym for ‘window’
  4. }-*/;

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:

JAVA:

  1. package org.example.yourcode.format.client;
  2. public class DateFormatterLib implements EntryPoint {
  3. // Expose the following method into JavaScript.
  4. private static String formatAsCurrency(double x) {
  5. return NumberFormat.getCurrencyFormat().format(x);
  6. }
  7. // Set up the JS-callable signature as a global JS function.
  8. private native void publish() /*-{
  9. $wnd.formatAsCurrency =
  10. @org.example.yourcode.format.client.
  11. DateFormatterLib::formatAsCurrency(D);
  12. }-*/;
  13. // Auto-publish the method into JS when the GWT module loads.
  14. public void onModuleLoad() {
  15. publish();
  16. }
  17. }
Advertisements
 
Leave a comment

Posted by on September 28, 2008 in GWT/ JSNI / COMPILER

 

Tags: ,

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

 
%d bloggers like this: