【问题标题】:How to call GWT java function from Javascript?如何从 Javascript 调用 GWT java 函数?
【发布时间】:2012-01-27 00:02:37
【问题描述】:

是否可以从 Javascript 调用 Java (GWT) 方法?从文档中也不清楚。 http://code.google.com/intl/ru/webtoolkit/doc/latest/DevGuideCodingBasicsJSNI.html 这里的所有示例都演示了从 JSNI(不是 JS)函数调用 java 函数。

更新 1

这是一段Java代码:

public class Test_GoogleWeb_JSNI_02 implements EntryPoint {
/**
 * This is the entry point method.
 */
public void onModuleLoad() {
}

public static void Callee() {
    Window.alert("Callee");
}
}

这是 html 中的调用者按钮示例:

<input type='button' value='Call' onclick='Test02()'>

下面是一些我尝试过但没有成功的功能:

<script type="text/javascript">

    function Test01() {
        @com.inthemoon.tests.client.Test_GoogleWeb_JSNI_02::Callee()();
    }

    function Test02() {
        com.inthemoon.tests.client.Test_GoogleWeb_JSNI_02::Callee()();
    }


</script>

更新 2

以下工作。

Java 准备:

public void onModuleLoad() {
    Prepare();
}

public static native void Prepare() /*-{
    $doc.calleeRunner = @com.inthemoon.tests.client.Test_GoogleWeb_JSNI_02::Callee();
}-*/;

public static void Callee() {
    Window.alert("Callee");
}

来电者:

function Test03() {
        document.calleeRunner();
}

有没有更好的办法?

【问题讨论】:

  • 你能调用一个返回对象的javascrypt方法吗?并使用那个对象?

标签: java javascript gwt jsni


【解决方案1】:

您的示例不起作用,因为您试图在某些外部脚本中使用 JSNI。如果你想从 external JS 调用某些东西,你需要使用 question 中描述的方法或使用 GWT exporter

更新:

公开 GWT 内容的最安全方法是将调用包装在其他函数中。例如:

    public native void expose()/*-{
    $wnd.exposedMethod = function(param){
         @com.my.MyClass::myFunction(*)(param);
    }
}-*/;

否则你可能会在生产模式下遇到一些奇怪的错误=)

【讨论】:

  • 谢谢!你更新关注我的Update2吗?我的意思是你建议不要写$wnd.exposedMethod=@com.my.MyClass::myFunction(*)(param)?为什么?
  • 它可能会阻止 GWT 进行一些基本的优化。性能影响很可能不会很大,但您应该牢记这一点。此外,您的方式仅适用于静态方法的公开,如果您尝试调用某些实例方法,它很可能会中断。
  • 你能调用一个返回对象的javascrypt方法吗?并使用那个对象?
  • 暴露的函数应该用$entry(...)函数包裹,见gwtproject.org/doc/latest/DevGuideCodingBasicsJSNI.html#calling: `$wnd.exposedMethod = $entry(function(param) {...});
  • 非静态方法可以这样调用吗?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-08-12
  • 2019-10-24
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多