Skip to content

Instantly share code, notes, and snippets.

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/d2d8c7019e297c103963494ce3fe6046 to your computer and use it in GitHub Desktop.
Save screamingworld/d2d8c7019e297c103963494ce3fe6046 to your computer and use it in GitHub Desktop.
JS/TS add/remove event listener with a defined method which returns an event handler
class UseDefinedMethodWhichReturnsEventHandler extends TestSetting {
public addEventListener() {
this.removeEventListener();
if (this.element == null) {
return;
}
this.element.addEventListener("click", this.onClickEventHandler);
}
public removeEventListener() {
if (this.element == null) {
return;
}
// does not remove the listener
this.element.removeEventListener("click", this.onClickEventHandler);
}
private onClickEventHandler(event: Event): Function {
return () => {
// 'this' is the instance of the class
console.log(this);
}
}
}
const useDefinedMethodWhichReturnsEventHandler = new UseDefinedMethodWhichReturnsEventHandler();
useDefinedMethodWhichReturnsEventHandler.addEventListener();
useDefinedMethodWhichReturnsEventHandler.addEventListener();
useDefinedMethodWhichReturnsEventHandler.simulateOnClick();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment