是否可以在 if 语句中嵌套 jQuery 事件侦听器?

Is it possible to nest a jQuery event listener inside an if-statement?

我正在尝试为已登录我页面的用户设置超时。我有一个从其他地方复制的工作超时功能,但我担心一个小问题。有问题的页面是一个单独的页面,它通过 jQuery/PHP 重新加载其内容,而不是将用户导航到另一个 URL.

事件侦听器检查任何用户 activity,并在发生这种情况时重置超时。我希望计时器仅在用户登录时 运行 ,并且一旦超时达到零,它就会将用户注销。当人们 login/logout/timeout.

时,我通过在 true 和 false 之间切换全局变量 idleEnabled 来实现这一点

我的问题:虽然超时函数仅在用户登录时在事件侦听器中可用,事件侦听器本身 永久激活并通过简单地移动鼠标不断地发出 ping 信号。我担心这可能会耗尽客户端浏览器的容量。

我有什么:我一直在寻找是否可以在 if (idleEnabled == true) { listener here } 中放置一个事件侦听器,但据我发现这是不可能的。即使是这样,我也很确定加载脚本时只有一个简单的 if 语句 运行,但是当页面本身没有重新加载时,相关变量会发生变化。

主要问题:请问有什么办法吗?或者这很好,我是否在担心一些无关紧要的事情?

附带问题:我读到过使用 javascript 全局变量是不可取的,但我不知道还有什么其他方法可以做到这一点。可以这样用吗?

相关jQuery代码:

//create a global timeout handle
var idleTimer = null;
var idleEnabled = false;
var idleWait = 10000; //This is low for testing purposes

//to prevent the timer from disappearing if people refresh the page,
//check if the logout button is on the page when loading the script:
if ($("#logout").length) {window.idleState = true;} 

$('*').on('mousemove keydown scroll', function () { //listen for activity

    if (idleEnabled == true) { //if the timer is enabled...

        clearTimeout(window.idleTimer); //...clear it,

        window.idleTimer = setTimeout(function () { //and reset it, so that...

            $(document).trigger("timeOut"); //...the custom timeout event fires
            window.idleEnabled = false; //...and the timer is disabled

        }, idleWait);

    } 
});

$(".column").on("click", "#login, #logout", {cause: "user"}, validateUser) //Call a validation on login/logout
$(document).on("timeOut", {cause: "timeout"}, validateUser) //Call a validation on timeout

//The function validateUser will set idleEnabled = true on login and idleEnabled = false on logout.

您绝对应该能够在 if 分支中添加侦听器。登录时,您需要重新设置。这是我的做法:

var idleTimer = null;
var idleWait = 10000;

// There is probably a better way to check if the user is logged in
function isLoggedIn() {
    return $("#logout").length > 0;
}

function setActivityListener(active) {
    if (active)
        $('*').on('mousemove keydown scroll', activityHandler);
    else
        $('*').off('mousemove keydown scroll');
}

function activityHandler() {
    clearTimeout(idleTimer);
    idleTimer = setTimeout(function () {    
        $(document).trigger("timeOut");
    }, idleWait);
};


if (isLoggedIn()) {
    setActivityListener(true);
}

$(".column").on("click", "#login, #logout", {cause: "user"}, validateUser);
$(document).on("timeOut", {cause: "timeout"}, validateUser);

// On login (in validateUser?)
setActivityListener(true);

// On logout
setActivityListener(false);