2

我正在使用 GWT 创建一个仅限客户端的库。我使用 JSNI 调用函数是来自 JS 的 Java。问题是我试图传递一个元素或一个函数处理程序,但似乎没有发生任何事情。我没有从 GWT 或 js 中得到异常。这是我的 JSNI 函数与网桥。

public static String testMe(Object obj) 
  {
      return "Response to " + obj.toString();     
  }

  public static native void defineBridgeMethod() /*-{
     $wnd.testMe = function(msg) {
        return @com.mycompany.mywebapp.client.MyWebApp::testMe(Ljava/lang/Object;);
     };

  }-*/;

谢谢!

4

2 回答 2

4

你没有使用msg,你的意思是用它作为参数调用函数:

public static native void defineBridgeMethod() /*-{
  $wnd.testMe = $entry(function(msg) {
    return @com.mycompany.mywebapp.client.MyWebApp::testMe(Ljava/lang/Object;)(msg);
  });
}-*/;

或者您可以将函数直接分配给窗口:

public static native void defineBridgeMethod() /*-{
  $wnd.testMe = $entry(
    @com.mycompany.mywebapp.client.MyWebApp::testMe(Ljava/lang/Object;)
  );
}-*/;
于 2012-11-29T23:24:33.920 回答
2

The easiest way to export a gwt project to js is using gwt-exporter. Gwtexporter allows to export any gwt project without writing a single line of jsni code and it has plenty of features which allows to customize classes and methods exposed to js, and even it could produce the documentation for your js api.

In your case, implement the Exportable interface in the class with your static method, and annotate your method.

public class MyClass implements Exportable {
  @Export("$wnd.testMe")
  public static String testMe(Object obj)  {
    return "Response to " + obj.toString();     
  }
}

Then you have to call the exportAll() method in your entry point and leave the gwt compiler and gwtexporter generator do their magic

public void onModuleLoad() {
  ExporterUtil.exportAll();
}

Here you have a tutorial of how to export a gwt-library to js, although the documentation of the project is quite good.

Some of the projects using this technique are chronoscope, gwtupload(jsupload) and gwtquery(jsquery).

于 2012-11-30T08:52:53.217 回答