触发一次后删除窗口事件处理程序

时间:2017-12-31 23:55:04

标签: javascript jquery

我正在处理一个奇怪的问题,我需要一个事件处理程序来绑定模块的实例化,但是当模块通过点击或按键终止时,我不再希望绑定这个全局事件。我已经获得了click事件来注册在代码中其他位置处理的模块的终止,这是有效的,但问题是我想要全局终止模块的转义按,无论我的用户当前在应用程序中的哪个位置。

我的问题是.off()在某些情况下似乎不起作用。

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.');
    }
}

我认为这种做法错了吗?我尝试将它绑定到div元素本身,但这有更多的包袱与聚焦div接收按键相关联,如果用户导航到另一个模块,将不再触发转义因为此模块将不再有焦点,好等等等。

谢谢!

这是小提琴: https://jsfiddle.net/rbfebL5y/1/

2 个答案:

答案 0 :(得分:2)

根据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.');
    }
}

答案 1 :(得分:1)

您可以使用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 
}

稍后如果要重置此功能,请执行

localStorage.removeItem('hasLoggedEscape');