簡體   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