GWT JSNI return a js-function


How can I return a JavaScript function from JSNI in GWT? I tried it the following way:

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

Store the function in a variable

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

Using the function afterwards produces the following error message:

(TypeError): object is not a function

Does somebody know how to solve this problem?

This works for me. Declare these methods:

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");
}-*/;

And then, you use these methods this way:

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

Lets consider you appName.nochache.js(GWT) in Homepage.html

in homepage.html

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

In your Gwt :

Within your Gwt source, you can access the sayHello() JS function through JSNI:

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

you can assign them to variables also

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

Note : if you are calling an js methods of any exterenal file that should be append on your html page with <script> tags...