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

时间:2016-02-11 10:18:59

标签: html gwt jsni

我想从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");
    }-*/;

但此代码不起作用。有人可以帮帮我吗?

2 个答案:

答案 0 :(得分:1)

尝试:

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");
}

这样的事情应该有效。 (可能有一些拼写错误。)

答案 1 :(得分:1)

GWT has JSNI and JSInterop. both can expose java api to js. this excerpt is taken from official gwt documentation.

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;

from urllib import request

a = 1

while a == 1:

    request.urlretrieve("http://lemerg.com/data/wallpapers/38/957049.jpg","D:\\Users\\Elias\\Desktop\\FolderName-957049.jpg")

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.

here's a link