1

I need to bridge a fairly procedural Javascript library consisting of some .js files containing functions to call from GWT.

There's already a nice utility called GWT-Exporter that does exactly the opposite (http://code.google.com/p/gwt-exporter/), I would need a kind of GWT-Importer, that generated automatically .java wrappers of the javascript functions.

I'm aware type is an issue here, but I'd be content if all return types became JavaScriptObject or primitives.

JSNI seems to be the way, but I'd want something that created the classes automatically instead of having to manually bind via JSNI all of the methods.

Fabio de Miranda
  • 1,096
  • 1
  • 8
  • 13

1 Answers1

3

This sounds like a job for JSNI.

http://code.google.com/webtoolkit/doc/latest/DevGuideCodingBasicsJSNI.html

If you know which functions you would like to call, it's fairly easy to set up a single utility class that contains static methods representing the functions in question.


Say you have a JavaScript library where you want to have the functions foo() and bar(number) exposed to your GWT application. You'll want to do the following.

  1. Put the JavaScript library in your war directory. (Not needed if externally hosted.)
  2. Include the script by adding a <script> tag to your host page
  3. Create the utility class

 

public final class LibraryName {

    public static native int foo() /*-{
        $wnd.foo(); // Use $wnd instead of window in JSNI methods
    }-*/;

    public static native void bar(double number) /*-{
       $wnd.bar(number)
    }-*/;

}

For a more in-depth article about JSNI, take a look at http://googlewebtoolkit.blogspot.com/2008/07/getting-to-really-know-gwt-part-1-jsni.html.

Wesley
  • 10,652
  • 4
  • 37
  • 52
  • Thanks a lot for the effort you put in your example. Sure JSNI is the way, but the library I need to call (WebGLU) has dozens of methods that I'd need to bind by hand. I'm searching for some sort of tool that could automate that process. – Fabio de Miranda Nov 10 '10 at 15:47
  • It would probably be worthwhile to update your question. Is there a global WebGLU object (like `$` with JQuery)? Otherwise, are the functions bound to the `window` object? The more specific you can be, the better the solution that can be provided. – Wesley Nov 10 '10 at 20:22
  • It seems like the link moved here: https://www.gwtproject.org/doc/latest/DevGuideCodingBasicsJsInterop.html . Can you please update your answer? – user8110579 Apr 28 '22 at 13:27