javascript - 使用 JsInterop 包装简单的 JavaScript 插件

标签 javascript gwt gwt2

我目前正在将我的 Gwt 2.7 项目升级到 2.8-beta1 并且我正在尝试从 JSNI 重构 Javascript 插件包装器到 JsInterop

这里是 JSNI 包装器:

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);
    }-*/;
}

我试过的:

@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);
}

问题是,我不知道如何包装构造函数。 在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,

所以,这是我的问题:如何包装一个 JavaScript 插件,在 JS 中构造函数看起来像 var myPlugin = MyPlugin({option1 : value1, option2 : value2,...}); 在 JsInterop 中?

感谢您的帮助:)

最佳答案

好的,我找到了解决方案。

只需声明一个带有参数和空内容的构造函数:

@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);
}

而且有效。

希望对其他人有帮助:)

编辑:MyPluginConfig 结构

MyPluginConfig 只是一个 POJO 类。

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

关于javascript - 使用 JsInterop 包装简单的 JavaScript 插件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36328176/

相关文章:

java - CellTable 在 TabLayoutPanel 中不可见

gwt - 使用 GWT,有没有办法不加载在 uibinder xml 文件中声明的小部件?

javascript - 混合内容 jQuery ajax HTTPS 请求已在 Laravel 上被阻止

javascript - 从动态字段计算数字

javascript - 如何为 RxJS Observable 的每次发射创建一个新对象?

javascript - 如何创建一个 java 脚本库 - 从头开始​​跟踪用户在网站上的操作?

google-app-engine - Google Web Toolkit (GWT) + Google App Engine (GAE) + 分离数据持久化

gwt - 使用 Google Web Toolkit 的服务器推送是否有良好的维护解决方案?

GWT 2.0.3 中的 String.split() 方法错误

database - GWT客户端HTML5数据库存储(Web SQL Database)