Created
January 16, 2022 21:02
-
-
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
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
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