GWT JSNI返回一个js函数

时间:2013-02-05 16:20:11

标签: javascript gwt d3.js

如何在GWT中从JSNI返回JavaScript 函数?我尝试了以下方式:

/* JSNI method returning a js-function */
public static native JavaScriptObject native_getFunction() /*-{
    return function(a,b){
        //do some stuff with a,b
    }
}-*/;

将函数存储在变量

/* outside from GWT: store the function in a variable */
JavaScriptObject myFunction = native_getFunction();

之后使用该函数会产生以下错误消息:

(TypeError): object is not a function

有人知道如何解决这个问题吗?

2 个答案:

答案 0 :(得分:6)

这对我有用。声明这些方法:

public static native JavaScriptObject native_getFunction() /*-{
    return function(a,b){
        //do some stuff with a,b
    }
}-*/;

private native void invoke(JavaScriptObject func)/*-{
    func("a", "b");
}-*/;

然后,您以这种方式使用这些方法:

JavaScriptObject func = native_getFunction();
invoke(func);

答案 1 :(得分:0)

让我们考虑一下appName.nochache.js(GWT)

中的Homepage.html homepage.html

中的

<script>
    function printMyName(name) {
        alert("Hello from JavaScript, " + name);
    }
    </script>

在你的Gwt中:

在你的Gwt源代码中,你可以通过JSNI访问sayHello()JS函数:

native void printMyNameInGwt(String name) /*-{
  $wnd.printMyName(name); // $wnd is a JSNI synonym for 'window'
}-*/;

您也可以将它们分配给变量

native void printMyNameInGwt(String name) /*-{
  var myname =$wnd.printMyName(name); // return that for your purposes
}-*/;

注意:如果你正在调用任何可以附加在你的html页面上的<script>标签的任何exterenal文件的js方法......