Last active
January 16, 2022 20:59
-
-
Save screamingworld/8e948800a2d318c2c808572fa76cc7a3 to your computer and use it in GitHub Desktop.
JS/TS add/remove event listener with an defined 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 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