Mark
Mark

Reputation: 575

trouble removing EventListeners from the listener

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.

Upvotes: 1

Views: 58

Answers (1)

DarkPurple141
DarkPurple141

Reputation: 290

You need to call .removeEventListener for every call you've made in adding it.

So from your code:

clickCatcher.removeEventListener('click', this.clickCatcherFunction);
window.removeEventListener('resize', this.clickCatcherFunction);
document.removeEventListener('keydown', this.clickCatcherFunction);

Mind, I'd be careful about pointing to this the way you are. this will be the enclosing object of the context you're calling is. Which may not be what you want.

Based on your edit:

document.addEventListener('keydown', this.clickCatcherFunction.bind(this));

Will help.

Upvotes: 1

Related Questions