JS/TS add/remove event listener with a local function saved in a instance var which uses
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 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