Skip to content

Instantly share code, notes, and snippets.

@screamingworld
Created January 16, 2022 21:05
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/4d8ee991be564564e9725d919dd83841 to your computer and use it in GitHub Desktop.
Save screamingworld/4d8ee991be564564e9725d919dd83841 to your computer and use it in GitHub Desktop.
JS/TS add/remove event listener with a local function saved in a instance var which uses
class Solution extends TestSetting {
private clickEventHandler:any;
public addEventListener() {
this.removeEventListener();
if (this.element == null) {
return;
}
var that = this;
this.clickEventHandler = function(event: Event) {
// 'this' is not the class instance but that is
console.log(that);
}
this.element.addEventListener("click", this.clickEventHandler);
}
public removeEventListener() {
if (this.element == null) {
return;
}
// does remove the listener
this.element.removeEventListener("click", this.clickEventHandler);
}
}
const solution = new Solution();
solution.addEventListener();
solution.addEventListener();
solution.simulateOnClick();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment