Wrap simple JavaScript plugin using JsInterop

2.2k Views Asked by At

i'm currently upgrading my Gwt 2.7 project to 2.8-beta1 and i'm trying to refactor the Javascript plugin wrapper from JSNI to JsInterop.

Here the JSNI wrapper :

public class MyPlugin extends JavaScriptObject {

    protected MyPlugin(){
    }

    public static native MyPlugin init(MyPluginConfig config) /*-{
        return new $wnd.MyPlugin(config);
    }-*/;

    public final native void addItem(MyPluginItem item) /*-{
        this.addItem(item);
    }-*/;

    public final native void setEnable(int itemIndex, boolean enable) /*-{
        this.setEnable(itemIndex, enable);
    }-*/;
}

What i've tried :

@JsType(namespace = JsPackage.GLOBAL, isNative = true)
public class MyPlugin {
    public static native MyPlugin init(MyPluginConfig config);
    public native void addItem(MyPluginItem item);
    public native void setEnable(int itemIndex, boolean enable);
}

The problem, i have no idea how to wrap the constructor. In the JsInterop doc

A native @JsType class can only have Public native methods, Public and uninitialized fields, Empty constructor, Final non-native methods that doesn’t override any other methods,

So, this is my question : How to wrap a JavaScript plugin where in the JS the constructor looks like var myPlugin = MyPlugin({option1 : value1, option2 : value2,...}); in JsInterop ?

Thanks for help :)

1

There are 1 best solutions below

3
Yoplaboom On BEST ANSWER

Ok, i found the solution.

Just declare a constructor with params and empty content :

@JsType(namespace = JsPackage.GLOBAL, isNative = true)
public class MyPlugin {
    public MyPlugin(MyPluginConfig config) {} //<--- here
    public native void addItem(MyPluginItem item);
    public native void setEnable(int itemIndex, boolean enable);
}

And it works.

Hope it helps other people :)

EDIT : MyPluginConfig structure

MyPluginConfig is just a POJO class.

@JsType(namespace = JsPackage.GLOBAL, isNative = true, name = "Object")
public class MyPluginConfig {
    @JsProperty public void setXXXX(String str);
    @JsProperty public String getXXXX();
    ...
}