Search code examples
gwtjsni

How to implement a javascript API using JSNI?


I am trying to implement an API (SCORM API) using GWT. The client code expects an API object with methods like Initialize(), getLastError() and so on...

I tried to implement this api as an Java Object, but i see that the compiled names are changed and cannot be used directly by client code.

I see that gwt-exporter can do the trick (http://code.google.com/p/gwt-exporter/) but i would like to know how to do it using pure gwt and jsni.

As the API is expected as a object, named API_1484_11 attached to the window object, not an function, , i don't see how to use the $entry() idiom.

Here is my current, failing, code:

public final class SCORMApi {

    protected SCORMApi() {}

    public void Initialize(){
        GWT.log("** INITIALIZE CALLED **");
    }

    public static void create(){
        bind(new SCORMApi());
    }

    public static native void bind(SCORMApi api) /*-{
        $wnd.API_1484_11 = api;
    }-*/;

}

So, in this context, my question is:

How can i get javascript calls (e.g. window.API_1484_11.Initialize() ) to reach my java gwt code?


Solution

  • You're on the right lines with your bind method. But you haven't understood how to call Java methods from within JSNI. This is how you do it in the case of your Initialize method:

    public static native void bind(SCORMApi api) /*-{
        $wnd.API_1484_11 = {
            initialize: function() {
                $entry( [email protected]::Initialize()() );
            }
        };
    }-*/;
    

    The blogs Getting To Really Know GWT parts 1 and 2 are required reading on this subject.