Amit Das Amit Das - 1 year ago 68
Javascript Question

Remove a window event Listener from the handler function

I have a function

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

My code:

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

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

Everything is working fine but it isn't removing the

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