simon
simon

Reputation: 964

Remove window event handler after triggered one time

I am dealing with an odd problem where I need an event handler to bind upon instantiation of a module, but when the module is terminated via a click or a keypress, I no longer want this global event bound. I've gotten the click event to register termination of the module handled elsewhere in code and that works, but the problem is the escape press that I want to globally terminate the module regardless of where my user currently is in the app.

My problem is that the .off() doesn't appear to work given the circumstances.

let tools = {};
//how can i eliminate this next line of code after escape has been triggered?
$(window).on('keydown', (e)=>escape(e, tools));
function escape(e, tools){
    if (e.which==27){
        //do some stuff with tools, etc
        $(window).off('keydown', $(window), escape); //this line doesn't seem to work
        alert('alert triggered, but next time escape is pressed it wont.');
    }
}

Am I going about this approach wrong? I tried binding it to the div element itself, but this has a whole lot more baggage associated with focussing the div to recieve the keypresses, and if the user navigates to another module, the escape will no longer be triggered because this module will no longer have focus, and well, etc etc etc.

Thank you!

Here is fiddle: https://jsfiddle.net/rbfebL5y/1/

Upvotes: 1

Views: 93

Answers (2)

bigless
bigless

Reputation: 3111

Use only handler function as argument according to documentation:

let tools = {};
//how can i eliminate this next line of code after escape has been triggered?
$(window).on('keydown', escape);
function escape(e){
    if (e.which==27){
        //do some stuff with tools, etc
        $(window).off('keydown', escape);
        alert('alert triggered, but next time escape is pressed it wont.');
    }
}

Upvotes: 2

Wesley Smith
Wesley Smith

Reputation: 19571

You could use localStorage:

// check key pressed and whether we've done this before
if (e.which==27 && !localStorage.getItem('hasLoggedEscape')){
    // set the local storage value saying we've done this before
    localStorage.setItem('hasLoggedEscape', 1);
    //do some stuff with tools, etc 
}

later if you want to reset this, do

localStorage.removeItem('hasLoggedEscape');

Upvotes: 1

Related Questions