简体   繁体   中英

Remove jQuery event listener when the handler needs to receive a callback function

I have a listener:

$(document).on("keypress", function(e){ebClose(e,mpClose)});

I am trying to figure out how to delete it dynamically. The challenge is that I really want ebClose to receive mpClose as a callback function, because in other instances ebClose would receive different callback functions.

What ebClose does is this:

function ebClose(e, callback){
    if (e.which == 13){
        callback();
    }
}

Which is to say, it checks if it is the enter key, and then calls the callback function. In theory, I could make 10 different versions of ebClose and paste in the different functions to avoid needing a callback, but it seems like it is a lot of code. Any suggestions out there for a strategy to be able to delete this listener when needed?

This obviously doesn't work:

$(document).off("keypress", function(e){ebClose(e,mpClose)});

And if I change it to this:

$(document).on("keypress", ebClose);

Then I can delete it, but don't know how to pass the callback. Thanks for suggestions.

One option is to namespace the events .

Example Here

// Attach a keypress event namespaced to 'ebclose'
$(document).on("keypress.ebclose", function(e) {
  ebClose(e, mpClose)
});

// Remove the namespaced event:
$(document).off("keypress.ebclose");

Alternatively, you could also use $.proxy() to bind the function:

Example Here

$(document).on("keypress", $.proxy(ebClose, this, mpClose));

function ebClose(callback, e){
    if (e.which == 13){
        callback();
    }
}
function mpClose () {
    alert('Remove the event listener');
    $(document).off("keypress", $.proxy(ebClose, this, mpClose));
}

Or, similarly, you could use the .bind() method :

Example Here

$(document).on("keypress", ebClose.bind(this, mpClose));

function ebClose(callback, e){
    if (e.which == 13){
        callback();
    }
}
function mpClose () {
    alert('Remove the event listener');
    $(document).off("keypress", ebClose.bind(this, mpClose));
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM