19

I am building a GWT app that uses Web SQL Local Storage ( http://dev.w3.org/html5/webdatabase/ ). The problem is that the Web SQL API uses callback functions as arguments.

Is it possible to pass "Java" callbacks to JSNI?

Julio Faerman
  • 13,228
  • 9
  • 57
  • 75

1 Answers1

22

Yes, it does:

private static native void doThingWithCallback() /*-{
  var self = this;
  var callbackFn = $entry(function(val) {
    self.@com.your.package.AClass.aMethod(Ljava/lang/String;)(val);
  });
  $wnd.someApiThatTakesACallback(callbackFn);
}-*/;

Two things to remember:

  1. $entry() reminds GWT to keep track of the code when using the debugger.
  2. var self = this keeps the reference to this inside the function -- otherwise this will be the function itself...
Jason Hall
  • 20,632
  • 4
  • 50
  • 57
  • 5
    You are supposed to have :: before the method name: self.@com.your.package.AClass::aMethod(Ljava/lang/String;)(val); – AmanicA Oct 25 '13 at 14:59
  • is this a javascript method or a java method? javascript doesn't have 'private static' and java doesn't have 'var'. – Ali Jan 11 '14 at 17:02
  • 1
    @ClickUpvote it's a GWT native method, which let's you write native JS in you GWT Java code. – Jason Hall Jan 11 '14 at 17:35