javascript 从 html 脚本标记调用 GWT Java 函数
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/5451840/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Calling a GWT Java function from an html script tag
提问by Mike
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.
我有一个 GWT 项目,我想向 GWT 项目的主 html 文件添加一个脚本标记,该文件调用位于我的客户端代码中的 Java 函数。
According to the documentationI should add something like the following html tag:
根据文档,我应该添加类似以下 html 标签的内容:
<script type='text/javascript'>
[email protected]::myFunction();
</script>
where com.myCompany.myProject.client.myClassis the class path and myFunctionis the java function I would like to call.
其中com.myCompany.myProject.client.myClass是类路径,而myFunction是我想调用的 java 函数。
When I try this with the following implementation of myFunction nothinghappens:
当我使用 myFunction 的以下实现尝试此操作时,没有任何反应:
public void myFunction() {
HTMLPanel panel = new HTMLPanel("I have been called");
RootPanel.get().add(panel);
}
That is, myFunctionis not being called.
也就是说,没有调用myFunction。
But when I make the same call from a JSNI method, then it works.
但是当我从 JSNI 方法进行相同的调用时,它就起作用了。
Is it maybe not possible to do the call from an html script, or am I doing something wrong?
是否可能无法从 html 脚本进行调用,或者我做错了什么?
Thanks!
谢谢!
回答by Peter Knego
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.You were looking at old version of documentation. In the latest version this is all explained: Calling a Java Method from Handwritten JavaScript
您尝试执行的操作不起作用,因为 GWT 编译器重命名所有标识符名称以最小化生成的代码大小:如此
myFunction()
存在,但它被称为其他名称。您正在查看旧版本的文档。在最新版本中,这一切都得到了解释: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:
然后在您的应用程序初始化中,您必须调用EnclosingClass.exportMyFunction()
. 然后在手工制作的 javascript 中,您可以通过以下方式访问它:
window.myFunction();