Amit Das Amit Das - 1 year ago 68
Javascript Question

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
.

Answer Source

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);
        }
    }
}
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download