In JavaScript, for an event handler that needs access to private members and functions, I can rely on the function scope of those to be accessible within my event handler functi
Already answered question, but IMO the answers here are not well designed regarding to OOP. So, here is my solution:
export class MyClass {
// create member that holds the function reference
protected clickEventListener: EventListener;
// inject the Element
constructor(protected theElement: Element) {
// wrap the class function `onClick` in an arrow function and assign
// to the class member `clickEventListener`
this.clickEventListener = () => this.onClick();
}
onClick() {
console.log("clicked");
}
init() {
// add the event listener to `theElement` and pass only the reference
// of `this.clickEventListener` (no round brackets '()')
this.theElement.addEventListener("click", this.clickEventListener);
}
destroy() {
// to remve the event listener also just pass the `clickEventListener` reference
this.theElement.removeEventListener("click", this.clickEventListener);
}
}