从 Java GWT 代码调用 .js 文件的 Javascript 函数
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/11986462/
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 Javascript function of .js file from java GWT code
提问by MS.
I have one button in Java GWT code. And I have one javascript file in scripts folder. I want to access functions of that js file on Button click.
我在 Java GWT 代码中有一个按钮。我在脚本文件夹中有一个 javascript 文件。我想在单击按钮时访问该 js 文件的功能。
So how can I call that method from Java GWT code(Button's click event)..?
那么如何从 Java GWT 代码(按钮的点击事件)调用该方法?
Can anyone please tell me code or way for accessing js file's function.
任何人都可以告诉我访问js文件功能的代码或方式。
Thanks in Advance.
提前致谢。
回答by Daniel Kurka
since your code should not depend on the gwt linker (and how it loads code) you need to prefix the call with the right window object. Reapp does not take that into account. So it actually needs to be:
由于您的代码不应依赖于 gwt 链接器(以及它如何加载代码),因此您需要在调用前加上正确的窗口对象。Reapp 没有考虑到这一点。所以它实际上需要是:
public static native void onMyButtonClick() /*-{
$wnd.myJSfunction();
}-*/;
回答by Johan S
- Import the JS Lib in your .html file.
Create a method like this:
public static native void onMyButtonClick() /*-{ myJSfunction(); }-*/;
Bind your button like this:
myButton.addClickHandler(new ClickHandler() { @Override public void onClick(ClickEvent event) { onMyButtonClick(); } });
Done!
- 在 .html 文件中导入 JS Lib。
创建一个这样的方法:
public static native void onMyButtonClick() /*-{ myJSfunction(); }-*/;
像这样绑定你的按钮:
myButton.addClickHandler(new ClickHandler() { @Override public void onClick(ClickEvent event) { onMyButtonClick(); } });
完毕!
Just make sure that the javascript containing your function is loaded before the generated GWT javascript.
只需确保在生成 GWT javascript 之前加载包含您的函数的 javascript。
Your welcome!
别客气!