Created
October 28, 2020 00:12
-
-
Save psygo/90d2363a3d2b32465229e3e4002f07d8 to your computer and use it in GitHub Desktop.
An "Autobind" Decorator in TypeScript
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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