Skip to content

Instantly share code, notes, and snippets.

@screamingworld
Last active January 16, 2022 20:59
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
Star You must be signed in to star a gist
Save screamingworld/8e948800a2d318c2c808572fa76cc7a3 to your computer and use it in GitHub Desktop.
JS/TS add/remove event listener with an defined event handler
class UseDefinedEventHandler extends TestSetting {
public addEventListener() {
this.removeEventListener();
if (this.element == null) {
return;
}
this.element.addEventListener("click", this.onClickEventHandler);
}
public removeEventListener() {
if (this.element == null) {
return;
}
// removes the listener succesfully
this.element.removeEventListener("click", this.onClickEventHandler);
}
private onClickEventHandler(event: Event): void {
// 'this' is no more the instance of the class
console.log(this);
}
}
const useDefinedEventHandler = new UseDefinedEventHandler();
useDefinedEventHandler.addEventListener();
useDefinedEventHandler.addEventListener();
useDefinedEventHandler.simulateOnClick();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment