A Rogue Otaku
A Rogue Otaku

Reputation: 923

Remove a window event Listener from the handler function

I have a function begin that declares an addEventListener with a handler function check. Now when a particular condition is satisfied inside check, I want to remove the eventListener.

My code:

function begin(data){
    //code
    window.addEventListener('keyUp', check(data));
}

function check(data){
    return function check1(event){
        //code
        if(condition) window.removeEventListener('keyUp', check(data));
    }
}

Everything is working fine but it isn't removing the EventListener.

Upvotes: 2

Views: 1953

Answers (3)

Leathan
Leathan

Reputation: 440

As others have pointed out your handler function is not check so you cant remove it. The handler function is the function check returns.

To better understand whats going on you can type.

check().prototype.constructor.name // 'check'
check.prototype.constructor.name   // 'check1'

Upvotes: 1

eisbehr
eisbehr

Reputation: 12452

You have to make the check(data) response function unique for the handler, like passing it to a variable. Otherwise you will get another function every time you call check(data) and you try to remove the wrong one.

var handler;

function begin(data) {
    handler = check(data);
    window.addEventListener('keyUp', handler);
}

function check(data) {
    return function check1(event) {
        if(condition) {
            window.removeEventListener('keyUp', handler);
        }
    }
}

Upvotes: 3

t.niese
t.niese

Reputation: 40882

The check1 will be always a different function for each call of check so you can remove itself using window.removeEventListener('keyup', check1 ):

function begin(data) {
  //code
  window.addEventListener('keyup', check(data));
}

function check(data) {
  return function check1(event) {
    if(condition) {
       window.removeEventListener('keyup', check1 );
    }
  }
}

Upvotes: 3

Related Questions