I am learning typescript on Udemy and the instructor is going through the method decorator to try to bind a method to the instance when it invoked in a event listener.
The way he did is to use decorator in TypeScript and amend the Property Descriptor.
Code is shown below.
function Autobind(_: any, _2: string, descriptor: PropertyDescriptor) {
const originalMethod = descriptor.value;
console.log(descriptor)
console.log(originalMethod)
const adjDescriptor: PropertyDescriptor = {
configurable: true,
enumerable: false,
get() {
const boundFn = originalMethod.bind(this);
return boundFn;
}
}
console.log(adjDescriptor)
return adjDescriptor;
}
class Printer {
message = 'This works!';
@Autobind
showMessage() {
console.log(this.message);
}
}
const p = new Printer();
const button = document.querySelector('button')!;
button.addEventListener('click', p.showMessage);
I have two questions on his method.
- How the 'get' method of the property descriptor get invoked in this case?
- Originally the descriptor has a value property which is the showMessage method. I am curious why he did not amend the value property. Instead, he is adding the get method to the descriptor and ignore the value property.