Skip to content

Instantly share code, notes, and snippets.

@screamingworld
Created January 16, 2022 21:01
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save screamingworld/bedf1b3723c0d6bf3439f9905e722233 to your computer and use it in GitHub Desktop.
Save screamingworld/bedf1b3723c0d6bf3439f9905e722233 to your computer and use it in GitHub Desktop.
JS/TS add/remove event listener with an anonymous event handler
class UseAnonymousEventHandler extends TestSetting {
public addEventListener() {
this.removeEventListener();
if (this.element == null) {
return;
}
this.element.addEventListener("click", () => {
// 'this' is the class instance
console.log(this);
});
}
public removeEventListener() {
if (this.element == null) {
return;
}
// does not remove the listener
this.element.removeEventListener("click", () => {});
}
}
const useAnonymousEventHandler = new UseAnonymousEventHandler();
useAnonymousEventHandler.addEventListener();
useAnonymousEventHandler.addEventListener();
useAnonymousEventHandler.simulateOnClick();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment