【问题标题】:Hot to model JSNI Functions with optional Parameters?使用可选参数对 JSNI 函数建模很热门?
【发布时间】:2014-03-11 01:00:20
【问题描述】:

我想为以下 JavaScript 函数编写一个 GWT JSNI 包装函数。

object.cache(config);

其中 config 是具有以下可选参数的对象

- x Number
- y Number
- width Number
- height Number
- length Number

我认为将函数参数的所有可能组合重写为 Java 函数并不好。

如何将这种带有许多可选参数的 JavaScript 函数建模为 JSNI Java 函数?

【问题讨论】:

    标签: java javascript html gwt jsni


    【解决方案1】:

    我会将配置对象建模为JavaScriptObject

    public class Config extends JavaScriptObject {
      protected Config() { }
    
      public native final boolean hasX() /*-{ return this.x == null; }-*/;
      public native final double getX() /*-{ return this.x || 0; }-*/;
      public native final void setX(double x) /*-{ this.x = x; }-*/;
      public native final void unsetX() /*-{ delete this.x; }-*/;
    
      …
    

    显然还有其他建模方法(例如使用java.lang.Double),但这种方法可能是编译后的 JS 输出中最轻量级的。

    或者您可以使用java.lang.Double 参数,但您将为包装对象付出代价:

    public native void cache(Double x, Double y, Double width, Double height, Double length) /*-{
      var cache = {};
      if (x != null) { cache.x = x.@java.lang.Double::doubleValue()(); }
      …
    

    最后,如果对您的情况有意义,您还可以使用特殊值:

    var config = {};
    if (x >= 0) { config.x = x; }
    

    【讨论】:

    • 为什么需要 hasX 和 unsetX?
    猜你喜欢
    • 1970-01-01
    • 2020-09-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-01-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多