gpt4 book ai didi

typescript - this.shadowRoot 来自装饰器内部

转载 作者:搜寻专家 更新时间:2023-10-30 21:29:47 25 4
gpt4 key购买 nike

我的自定义 HTMLElements 中的大多数事件处理程序看起来像这样,

  totalChanged() {
if (!this.shadowRoot) return
const t = this.shadowRoot.querySelector('#total')
if (t) t.innerHTML = String(this.price * this.quantity)
}

有没有可能让它看起来像

  @event('#total')
totalChanged() {
return String(this.price * this.quantity)
}

不知道如何到达装饰器中的 shadowRoot,this 指的是装饰器模块本身,而不是 HTMLElement。而proto是我自定义元素的原型(prototype),也不是我想要的this

export function event(select: string) {
return (proto: any, propName: string) : any => {
console.log(this.shadowRoot)
}
}

这里 this 只是未定义

export function event(select: string) {
return function (proto: any, propName: string) : any {
console.log(this.shadowRoot)
}
}

编辑:示例

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";
}
}
}

function myevent(select: string) {
return function (this:any, proto: any, propName: string, descriptor: PropertyDescriptor) : any {
let originalMethod = descriptor.value;
descriptor.value = function(this:any, ...args: any[]) {
console.log('test', this)
return originalMethod.apply(this, args)
}
return descriptor;
}
}

@defineClass('test-2')
class Greeter2 extends HTMLElement{
property = 'property2'
hello = 'hello2'
constructor() {
super()
console.log(this.hello)
}
@myevent('hello')
helloFn() {}
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)
}
@myevent('hello')
helloFn(){}
}
console.log('test-3: ', new Greeter3());

EDIT2:需要调用方法 new Greeter3().helloFn() 请参阅 Diullei 回答

最佳答案

它缺少访问对象上下文的descriptor 参数。试试这个代码:

export function event(select: string) {
return function (proto: any, propName: string, descriptor: PropertyDescriptor) : any {
let originalMethod = descriptor.value; // saving the original function

descriptor.value = function(...args: any[]) { // changing the original function body
console.log(this.shadowRoot);
return originalMethod.apply(this, args); // calling original function
}
return descriptor;
}
}

关于typescript - this.shadowRoot 来自装饰器内部,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43018143/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com