Wednesday, July 23rd, 2008

Getting to know GWT JSNI; Including talking to GWT code from JavaScript

Category: GWT, JavaScript

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:

  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?

  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.  
  9.   private void onFlip(String flippedName) {
  10.     // do something useful with the flipped name
  11.   }
  12. }

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

  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:

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

For more, check out this talk on the topic given by the GWT architect Scott Blum:

Posted by Dion Almaer at 6:43 am
Comment here

+++--
3.9 rating from 21 votes

Comments Here »

Comments feed TrackBack URI

Leave a comment

You must be logged in to post a comment.