让我再解释一下关于将 GWT 内容导出到 JS 世界的内容。您有多种选择,但我将重点介绍三种方法。
[编辑]
0- JsInterop:GWT 维护人员正在开发一项新功能,以便轻松地将 java 方法导出到 javascript,并包装 javascript 对象。该功能在 2.7.0 中是非常实验性的,缺少一些功能,但在 2.8.0 中几乎可以使用。请查看设计文档,以及邮件列表中的其他讨论。
[结尾]
1- JSNI:第一个是编写你自己的jsni,在这种情况下你必须意识到你可能犯的错误。基本上这些错误是因为你必须知道如何处理类型。在您的情况下,如果您想获得一个 javascript 数组(就像您在下面的评论中询问的那样),解决方案可能是:
public static native void exportMyFunction()/*-{
$wnd.handleAnchorClick = @company.package.class.JSNITest::handleAnchorClick(*);
}-*/;
public static void handleAnchorClick(JsArrayMixed args) {
Window.alert("Current row and Column is " +
args.getNumber(0) + " " + args.getNumber(1));
}
public void onModuleLoad() {
exportMyFunction();
}
//javascript code
window.handleAnchorClick([1,2])
请注意,JSNI 只允许您传递primitive
类型(long 除外)和JavaScriptObject
对象。因此,当传递一个 javascript 数组时,您必须JavaScriptObject
在示例中使用 like 来接收它。在这种情况下,由于 javascript 仅使用数字类型,args.getNumber
因此将始终返回双精度值,并且您必须在 java 中进行转换。
2- gwt-exporter用于导出大型项目,或者当您需要处理复杂的对象和类时,我宁愿使用gwt-exporter
static class MyClass implements Exportable {
@Export("$wnd.handleAnchorClick")
public static void handleAnchorClick(double[] args) {
Window.alert("Current row and Column is " +args[0] + " " + args[1]);
}
}
public void onModuleLoad() {
GWT.create(MyClass.class);
}
//javascript code
window.handleAnchorClick([1,2])
gwt-exporter 将处理任何类型的原始类型(即使是 long)myfunc(long[] args)
,使用 var-args myfunc(long...args)
,它支持方法重载等等。
3- gwtquery最后,如果您更喜欢gwtquery,您可以使用一种技术将函数属性添加到任何 js 对象,例如window
// The GQuery Properties object is able to wrap a java Function object
// into an js property.
Properties wnd = window.cast();
wnd.setFunction("handleAnchorClick", new Function() {
public void f() {
// Get the js arguments[] array
JsArrayMixed args = arguments(0);
// Get the first element of the arguments[] array
JsArrayMixed ary = args.getObject(0);
Window.alert("Current row and Column is " +
ary.getNumber(0) + " " + ary.getNumber(1));
}
});
//javascript code
window.handleAnchorClick([1,2])
使用 gquery,您可以使用 gwtJsArrayMixed
类,它总是将数字作为双精度返回,或者您可以使用JsCache
允许将数字转换为 java 中的任何其他数字类型的a((JsCache)ary.get(1, Integer.class)
作为总结,我宁愿使用gwt-exporter作为第一个选项,因为它专门处理这个问题。作为第二种选择,我会使用gquery,它是 gwt 的重要补充。最后,我会尽可能避免使用手写jsni,Javascript 通常是问题和错误的根源(认为 gwt 的主要目标不是处理 js)。