让我详细解释一下如何将 GWT 内容导出到 JS 世界。您有多种选择可以做到这一点,但我将重点介绍三种方法。
[EDITED]
0- Js互操作:GWT 维护者正在开发一项新功能,可以轻松地将 java 方法导出到 javascript,并包装 javascript 对象。该功能在 2.7.0 中是非常实验性的,缺少一些功能,但在 2.8.0 中几乎可以正常使用。请查看设计文件 https://docs.google.com/document/d/1tir74SB-ZWrs-gQ8w-lOEV3oMY6u6lF2MmNivDEihZ4/edit, 和别的在邮件列表中。
[END]
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
就像示例中一样。在这种情况下,由于 javascript 仅使用数字类型,args.getNumber
将始终返回双精度值,并且您必须在 java 中进行转换。
2- gwt-出口商对于导出大型项目,或者当您需要处理复杂的对象和类时,我宁愿使用gwt-出口商 http://code.google.com/p/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 参数myfunc(long...args)
,它支持方法重载等等。
3- gwtquery最后如果你愿意的话gwtquery https://code.google.com/p/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中的任何其他数字类型((JsCache)ary.get(1, Integer.class)
作为总结,我宁愿使用gwt-出口商作为第一个选项,因为它专门处理这个问题。作为第二个选择,我会使用gquery这是对 gwt 的重要补充。最后,我会避免使用手写jsni如果可能的话,Javascript 通常是问题和错误的根源(认为 gwt 的主要目标不是处理 js)。