heybran / vite-babel-proposal-decorators

2 stars 0 forks source link

Related discussions #1

Open vollowx opened 1 year ago

vollowx commented 1 year ago

不经过简化的自定义元素属性看起来是这样的

  // ...
  /**
   * @param {boolean} value
   */
  set checked(value) {
    this.toggleAttribute('checked', value);
  }
  get checked() {
    return this.hasAttribute('checked');
  }
  // ...

想通过装饰器达成这样的效果

  @property(Boolean) checked = false;

但是不知道怎么在装饰器里访问实例化的元素,这是失败的方式

/**
 * @param {BooleanConstructor|StringConstructor} type
 */
export function property(type) {
  /**
   * @param {Object} target
   * @param {string} name
   */
  return (target, name) => {
    if (type === Boolean)
      Object.defineProperty(target, name, {
        get() {
          return target.hasAttribute(name);
        },
        set(flag) {
          target.toggleAttribute(name, Boolean(flag));
        },
      });
    else if (type === String)
      Object.defineProperty(target, name, {
        get() {
          return target.getAttribute(name);
        },
        /**
         * @param {string} val
         */
        set(val) {
          target.setAttribute(name, val);
        },
      });
  };
}

求指教 :thinking: