Skip to content

Instantly share code, notes, and snippets.

@psygo
Created October 28, 2020 00:12
Show Gist options
  • Save psygo/90d2363a3d2b32465229e3e4002f07d8 to your computer and use it in GitHub Desktop.
Save psygo/90d2363a3d2b32465229e3e4002f07d8 to your computer and use it in GitHub Desktop.
An "Autobind" Decorator in TypeScript
// From Max Schwarzmüller's Understanding TypeScript - 2020 Edition on Udemy.
// A method is just a function with a property as a value.
function Autobind(_: any, __: string, descriptor: PropertyDescriptor) {
const originalMethod = descriptor.value;
const adjDescriptor: PropertyDescriptor = {
configurable: true,
enumerable: false,
get() {
const boundFn = originalMethod.bind(this);
return boundFn;
}
};
return adjDescriptor;
}
class Printer {
message = 'This works!';
@Autobind
showMessage() {
console.log(this.message);
}
}
const p = new Printer();
p.showMessage();
const button = document.querySelector('button');
// The `this` keyword with event listeners... you have to bind stuff without an autobind decorator.
// button.addEventListener('click', p.showMessage.bind(p));
button.addEventListener('click', p.showMessage);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment