从 gwt 中的 html 标记调用 gwt 方法

call gwt method from html tag in gwt

我想从 html 标记调用 gwt 方法。我做到了

 public void onModuleLoad(){
         HTML html = new HTML("<button onclick=\"javascript:fire();\">test</button>");
         RootPanel.get().add(html);
    }

    private static  native void  fire()/*-{
      $wnd.alert("clicked");
    }-*/;

但是这段代码不起作用。有人可以帮助我吗?

尝试:

Button tb = new Button("test");
tb.addClickHandler(new ClickHandler() {
  @Override
  public void onClick(ClickEvent event) {
    fire();
  }
});
RootPanel.get().add(tb);

private void fire() {
  com.google.gwt.user.client.Window.alert("clicked");
}

像这样的东西应该有用。 (可能有一些错别字。)

GWT 有 JSNI 和 JSInterop。两者都可以将 java api 暴露给 js。此摘录摘自官方 gwt 文档。

Calling a Java Method from Handwritten JavaScript

Sometimes you need to access a method or constructor defined in GWT from outside JavaScript code. This code might be hand-written and included in another java script file, or it could be a part of a third party library. In this case, the GWT compiler will not get a chance to build an interface between your JavaScript code and the GWT generated JavaScript directly.

A way to make this kind of relationship work is to assign the method via JSNI to an external, globally visible JavaScript name that can be referenced by your hand-crafted JavaScript code. package mypackage;

public MyUtilityClass
{
    public static int computeLoanInterest(int amt, float interestRate,
                                          int term) { ... }
    public static native void exportStaticMethod() /*-{
       $wnd.computeLoanInterest =
          $entry(@mypackage.MyUtilityClass::computeLoanInterest(IFI));
    }-*/;
}

Notice that the reference to the exported method has been wrapped in a call to the $entry function. This implicitly-defined function ensures that the Java-derived method is executed with the uncaught exception handler installed and pumps a number of other utility services. The $entry function is reentrant-safe and should be used anywhere that GWT-derived JavaScript may be called into from a non-GWT context.

On application initialization, call MyUtilityClass.exportStaticMethod() (e.g. from your GWT Entry Point). This will assign the function to a variable in the window object called computeLoanInterest.

这里是 link