Search code examples
gwtjsni

JSNI dynamic function reference in GWT


I would like to call arbitrary js function from gwt. Function name would be inside functionname variable. Something like this:

private static native String execute(String functionName, JavaScriptObject data) /*-{
    return $wnd.functionName(data);
}-*/;

I assume that something like this could be possible, but how to create fn variable to represent my arbitrary functionname function.

private static native String execute(JavaScriptObject fn, JavaScriptObject data) /*-{
    return fn(data);
}-*/;

Solution

  • If you need to invoke function by name, you need to do something like this:

    private static native String execute(String functionName,JavaScriptObject data)/*-{
         $wnd[functionName](data);
    
    }-*/;
    

    To get reference to a function you will need to use JSNI like this:

    private static native JavaScriptObject getFunction(String functionName)/*-{
        return  $wnd[functionName];
    
    }-*/;