GWT:如何执行作为参数传递的本机 js 函数(因此无法全局访问)
GWT: How to execute native js function passed as param (and thus not accessible globally)
这是重现我正在努力解决的问题的最小代码片段:
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 消费者(或任何其他功能接口)的本机函数?
您必须将 resolve
设为 JavaScriptObject
而不是 Consumer<String>
,并使用 JSNI 调用它:
private native void call(JavaScriptObject resolve, String arg) /*-{
resolve(arg);
}-*/;
虽然你真的应该在这里使用 JsInterop,有一个 @JsFunction
接口;并且可能实际上只是使用 Elemental 2 的 Promise
.
映射
这是重现我正在努力解决的问题的最小代码片段:
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 消费者(或任何其他功能接口)的本机函数?
您必须将 resolve
设为 JavaScriptObject
而不是 Consumer<String>
,并使用 JSNI 调用它:
private native void call(JavaScriptObject resolve, String arg) /*-{
resolve(arg);
}-*/;
虽然你真的应该在这里使用 JsInterop,有一个 @JsFunction
接口;并且可能实际上只是使用 Elemental 2 的 Promise
.