typescript - 從裝飾器內部訪問 this.shadowRoot
我自訂的 HTML 元素中的大多數事件處理函式看起來像這樣,
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 是我自訂元素的原型,也不是我想要的 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 的回答
答案#1
缺少 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;
}
}
