Javascript GWT JSNI返回一个js函数

Javascript GWT JSNI返回一个js函数,javascript,gwt,d3.js,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

如何在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

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

这对我很有用。声明以下方法:

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);

让您考虑<代码> AppNo.NoChay.JS(GWT) <代码>主页。

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

<script>
    function printMyName(name) {
        alert("Hello from JavaScript, " + name);
    }
    </script>
您还可以将它们分配给变量

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

注意:如果您正在调用任何外部文件的js方法,这些外部文件应该附加在html页面上,并带有
标记…

为什么需要这样做???返回的函数是一个d3.js转换函数,在其他几个JSNI方法中用于转换某些数据。为了避免冗余并动态更改转换,我希望将其存储在变量中。我不明白为什么您不能从其他JSNI方法调用此JS函数,就像您调用文档中的任何JS一样,而不将其存储在变量中。(1)为什么不直接调用该函数:正如我所说的,它是来自d3.js的转换函数,但带有我编写的自定义参数。因此,每当我在任何JSNI方法中需要转换函数时,我都必须再次编写转换函数(重复代码,可维护性)。(2) 因此,我只定义一次函数,将其存储在变量中,然后可以将此函数作为参数提供给任何需要转换的JSNI方法。您可以定义JS函数,将其注入文档(使用GWT ScriptInjector),并直接从任何JSNI方法调用它。但是我喜欢Simon Pierre的解决方案,我认为将相关方法提取到html页面也是一个不错的解决方案。谢谢