繁体   English   中英

GWT JSNI返回一个js函数

[英]GWT JSNI return a js-function

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

让我们考虑您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
}-*/;

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM