Search code examples
javajavascriptgwtjsni

JSNI Wrapper object


Here is a common way to access JS methods:

public class JSNIHelper {
    public static native void errorNotify(String _title, String _text) /*-{
        $wnd.$.pnotify({
                                        title: _title,
                                        text: _text,
                                        type: 'error'
                                })
        }-*/; 
}

However is there a "object wrapper" on top of the JSNI to access Javascript in a more Java object way like:

JSNIWrapper().call("$").method("pnotify")
.set("title", title)
.set("text", text)
.set("type", type).now();

I'm not entirely sure as what is the best implementation, I'm not a JS expert. So my question would be if there's any existing JSNI object wrapper that exist?


Solution

  • gwtquery is a good complement for GWT, it has plenty of helpers which facilitates interact with javascript without writing jsni, etc.

    In your case your code could be something like:

    // Create a JSO and set the properties
    Properties p =  Properties.create();
    p.set("title", title);
    p.set("text", text);
    p.set("type", type);
    
    // Get the JSO which has the function we want to call
    JavaScriptObject $ = JsUtils.prop(window, "$");
    
    // Call the JS method and get the result (null if the native
    // js function returns void
    Object ret = JsUtils.runJavascriptFunction($, "pnotify", p);
    

    BTW: the chaining syntax you are proposing makes perfect sense, so you could propose this feature as an enhancement to the gquery Properties object. Something like:

    $$().set("title", title).set("text", text).set("type", type).call(window, "$.pnotify");