Is there any way to automatically bridge a Javascript library to GWT?

荒凉一梦 提交于 2019-12-11 12:37:31

问题


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.


回答1:


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.



来源:https://stackoverflow.com/questions/4138887/is-there-any-way-to-automatically-bridge-a-javascript-library-to-gwt

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!