如何装饰Web Component类

问题描述 投票:2回答:1

我正在创建一个@Component装饰器,它会在一个类的构造函数之后进行构建,以便在构造之后执行一些工作。从以下代码中可以看出,该工作是在init方法中实现的。

export function Component (Cls) {
  function Class (...args) {
    let self = new Cls (...args); // (1)
    init (self, ...args);
    return self;
  }
  Class.prototype = Cls.prototype;
  return Class;
}

当我在普通类上测试这段代码时,一切正常。这是一个有效的例子:

class Base { ... }

@Component
class Core extends Base {
  constructor () {
    super (); // init is invoked
  }
  fx () { console.log ('Core.fx') }
  fy () { console.log ('Core.fy') }
}

然而,当我尝试装饰web组件时,获得了TypeError: Illegal constructor消息。

@Component
class Core extends HTMLElement {
  constructor () {
    super ();
  }
  fx () { console.log ('Core.fx') }
  fy () { console.log ('Core.fy') }
}
customElements.define ('x-core', Core);

let coreX = document.createElement ('x-core');
document.body.appendChild (coreX);

我意识到问题是HTMLElement不支持通过new运算符直接构造 - 请参阅第一个列表中的(1) - 但我需要一个程序来装饰任何类的构造函数,即使它们是自定义元素。

一些想法?

工作设置:Chrome 68·Babel 7.0.0-beta.51,带有babel-plugin-transform-decorators-legacy

javascript custom-element
1个回答
0
投票

你可以返回一个类,以避免直接new

function Component(cls) {
  class c extends cls {
    constructor() {
      super()
      console.log(this)//init
    }
  }
  return c
}
© www.soinside.com 2019 - 2024. All rights reserved.