【问题标题】:custom elements and class decorators自定义元素和类装饰器
【发布时间】:2017-03-25 04:13:28
【问题描述】:

自定义元素对类装饰器的作用不同?

例子:

index.html

<test-2></test-2>
<script src="test2.js"></script>

test2.ts => test2.js(目标:es2017)

function defineClass(tagname: string) {
  return function classDecorator<T extends {new(...args:any[]):{}}>(constructor:T) {
    console.log("Define: " + constructor.name)
    window.customElements.define(tagname, constructor)
    return class extends constructor {
        newProperty = "decorator";
        hello = "decorator";
    }
  }
}

@defineClass('test-2')
class Greeter2 extends HTMLElement{
  property = 'property2'
  hello = 'hello2'
  constructor() {
    super()
    console.log(this.hello)
  }
  connectedCallback() { }
  disconnectedCallback() { }
  attributeChangedCallback(name: string, oldValue: string, newValue: string) { }
  adoptedCallback() { }
}
console.log('test-2: ', document.querySelector('test-2').hello)

@defineClass('test-3')
class Greeter3 {
  property = 'property3'
  hello = 'hello3'
  constructor() {
    console.log(this.hello)
  }
}
console.log('test-3: ', new Greeter3());

输出:

Define: Greeter2
hello2
test-2:  hello2 <= expected "decorator" like Greeter3 does

Define: Greeter3
hello3
test-3: Object {property: "property3", hello: "decorator", newProperty: "decorator"}

这是它假设的工作方式吗?如果有,为什么?

【问题讨论】:

    标签: typescript custom-element


    【解决方案1】:

    感谢https://github.com/rictic 寻找解决方案,问他是否有时间在堆栈上回答,但不认为他有帐户,所以我将其粘贴。

    function defineClass(tagname: string) {
      return function classDecorator<T extends {new(...args:any[]):{}}>(constructor:T) {
        console.log("Define: " + constructor.name)
        const generated = class extends constructor {
            newProperty = "decorator";
            hello = "decorator";
        }
        window.customElements.define(tagname, generated)
        return generated;
      }
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2013-02-06
      • 1970-01-01
      • 1970-01-01
      • 2020-05-19
      • 2011-09-17
      • 2020-09-04
      • 1970-01-01
      相关资源
      最近更新 更多