Getting to know GWT JSNI; Including talking to GWT code from JavaScript
Date : 2008 07 23 Category : Tech & DevelopmentBruce 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: // Java method declaration... native String flipName(String name) /*-{ // ...implemented with JavaScript var re = /(w+)s(w+)/; return name.replace(re, '$2, $1'); }-*/;But what about calling back out to Java from within native land?
PLAIN TEXT JAVA: package org.example.foo; public class Flipper { public native void flipName(String name) /*-{ var re = /(w+)s(w+)/; var s = name.replace(re, '$2, $1'); this.@org.example.foo.Flipper::onFlip(Ljava/lang/String;)(s); }-*/; private void onFlip(String flippedName) { // do something useful with the flipped name } }You can also access any JavaScript, loaded from a script source or however via:
PLAIN TEXT JAVA: // A Java method using JSNI native void sayHelloInJava(String name) /*-{ $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:
PLAIN TEXT JAVA: package org.example.yourcode.format.client; public class DateFormatterLib implements EntryPoint { // Expose the following method into JavaScript. private static String formatAsCurrency(double x) { return NumberFormat.getCurrencyFormat().format(x); } // 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: