GWT:如何执行作为param传递的本机js函数(因此无法全局访问)

时间:2017-10-25 22:58:05

标签: javascript gwt jsni

这里是重现我遇到的问题的最小代码片段:

import java.util.function.Consumer;

public class NaivePromise<T> {

  public NaivePromise(Consumer<Consumer<T>> resolve) {
    super();
    create(resolve);
  }

  public native NaivePromise<T> create(Consumer<Consumer<T>> handler) /*-{
    return new Promise(function (resolve) {
      console.log("DBG NATIVE RESOLVE");
      handler.@java.util.function.Consumer::accept(*)(resolve)
    });
  }-*/;


  public static void pong() {
    new NaivePromise<String>(resolve -> {
      resolve.accept("HERE WE'LL GET AN ERROR, SINCE RESOLVE IS ACTUALLY A NATIVE FUNCTION");
    });
  }

}

我的问题是 - 如何执行作为lambda传递给GWT Consumer(或任何其他功能接口)的本机函数?

1 个答案:

答案 0 :(得分:3)

您必须使resolve成为JavaScriptObject而不是Consumer<String>,并使用JSNI来调用它:

private native void call(JavaScriptObject resolve, String arg) /*-{
  resolve(arg);
}-*/;

虽然你真的应该在这里使用JsInterop,使用@JsFunction接口;实际上可能只是使用元素2的Promise映射。