In my JS module I have a function that adds a couple event listeners
clickCatcher.addEventListener("click", this.clickCatcherFunction);
window.addEventListener('resize', this.clickCatcherFunction);
document.addEventListener('keydown', this.clickCatcherFunction);
and the function clickCatcherFunction is called, all good so far. Now it's time to remove all the event listeners if one of them triggered.
document.removeEventListener('keydown', this.clickCatcherFunction);
No errors, but the event listeners are still active. How do I access the same function that I passed in? Inside the listener function, this.someOtherFunc also fails. What's the scope of this listener, has it changed?
Edit. Adding more for context:
export default class Hints {
constructor(){
//ref for adding and removing
this.clickCatcherFunction = this.clickCatcherFunction.bind(this);
//add invisible top div to catch click and remove hint,
const clickCatcher = document.createElement("div");
clickCatcher.id = "clickCatcher";
document.body.appendChild(clickCatcher);
clickCatcher.addEventListener('click', this.clickCatcherFunction);
window.addEventListener('resize', this.clickCatcherFunction);
document.addEventListener('keydown', this.clickCatcherFunction);
}
clickCatcherFunction() {
//clickCatcher gets deleted from the dom
document.removeEventListener('keydown', this.clickCatcherFunction);
window.removeEventListener('resize', this.clickCatcherFunction);
}
}
//in the JS that imported Hints.JS
import Hints from "../Hints.js"
let hint = new Hints();
Adding solution into constructor.