【问题标题】:How to decorate a Web Component class如何装饰 Web 组件类
【发布时间】:2019-02-06 12:41:05
【问题描述】:

我正在创建一个 @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

【问题讨论】:

  • 如果您根本不能使用new,您将如何使用CoreComponent 在这里并不重要,恕我直言。
  • 非常感谢@appleapple 我已经完成了后者的sn-p。在我的第一次修订中,我没有包含最后 3 行,因此存在相同的问题,但没有触发错误。

标签: javascript custom-element


【解决方案1】:

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

function Component(cls) {
  class c extends cls {
    constructor() {
      super()
      console.log(this)//init
    }
  }
  return c
}

【讨论】:

  • 很好的解决方案@appleapple。问题是这种方法非常具有侵入性。你正在增加继承链,所以我的很多测试都被打破了。通过装饰架构找到一个子类,它应该是父(原始级别)类
  • @JavierVélez 我不明白你在说什么。装饰类正在取代原始类。您应该不会注意到任何差异。
  • 举个例子,在我架构的其他地方,我需要通过Object.getOwnPropertyNames 恢复类成员。现在这种方法在架构上运行良好。如果你通过@Component 装饰器生成一个新的子类,Object.getOwnPropertyNames 返回 [] 所以整个架构失败了。我不能假设整个体系结构都会发生这种关键变化,因为并非所有目标类都将由@Component 装饰
猜你喜欢
  • 2017-10-17
  • 2016-08-18
  • 1970-01-01
  • 1970-01-01
  • 2016-12-25
  • 2019-11-06
  • 2019-03-06
  • 2019-02-03
相关资源
最近更新 更多