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.
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.
- Put the JavaScript library in your
war
directory. (Not needed if externally hosted.)
- Include the script by adding a
<script>
tag to your host page
- 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.