开发者

Calling a GWT Java function from an html script tag

开发者 https://www.devze.com 2023-02-19 22:18 出处:网络
I have a GWT project and I would like to add a script tag to the main html file of the GWT project that calls a Java function located in my client code.

I have a GWT project and I would like to add a script tag to the main html file of the GWT project that calls a Java function located in my client code.

According to the documentation I should add something like the following html tag:

<script开发者_JAVA技巧 type='text/javascript'> 
this.@com.myCompany.myProject.client.myClass::myFunction();
</script>

where com.myCompany.myProject.client.myClass is the class path and myFunction is the java function I would like to call.

When I try this with the following implementation of myFunction nothing happens:

public void myFunction() {
    HTMLPanel panel = new HTMLPanel("I have been called");
    RootPanel.get().add(panel);
}

That is, myFunction is not being called.

But when I make the same call from a JSNI method, then it works.

Is it maybe not possible to do the call from an html script, or am I doing something wrong?

Thanks!


  1. What you are trying to do does not work because GWT compiler renames all identifier names to minimize produced code size: so myFunction() exists, but it's called something else.

  2. You were looking at old version of documentation. In the latest version this is all explained: Calling a Java Method from Handwritten JavaScript

The solution - add an additional method somewhere:

public static native void exportMyFunction() /*-{
   $wnd.myFunction =
      $entry(@com.myCompany.myProject.client.myClass::myFunction());
}-*/;

then in your app initialization you must call EnclosingClass.exportMyFunction(). Then in hand-crafted javascript you can access it via:

window.myFunction();
0

精彩评论

暂无评论...
验证码 换一张
取 消