GWT JSNI returns js function
How to return JavaScript function from JSNI to GWT? I tried it like this:
/* JSNI method returning a js-function */
public static native JavaScriptObject native_getFunction() /*-{
return function(a,b){
//do some stuff with a,b
}
}-*/;
Storing a function in a variable
/* outside from GWT: store the function in a variable */
JavaScriptObject myFunction = native_getFunction();
Using the function afterwards, you receive the following error message:
(TypeError): object is not a function
Does anyone know how to fix this problem?
source to share
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 like this:
JavaScriptObject func = native_getFunction();
invoke(func);
source to share
Let's take you appName.nochache.js(GWT)
inHomepage.html
in Homepage.html
<script>
function printMyName(name) {
alert("Hello from JavaScript, " + name);
}
</script>
In your Gwt:
In your Gwt source, you can access the saySello () JS function via JSNI:
native void printMyNameInGwt(String name) /*-{
$wnd.printMyName(name); // $wnd is a JSNI synonym for 'window'
}-*/;
you can also assign them to variables
native void printMyNameInGwt(String name) /*-{
var myname =$wnd.printMyName(name); // return that for your purposes
}-*/;
Note: if you call js methods of any exterenal file that needs to be added to your tagged html page <script>
...
source to share