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

问题描述 投票:0回答:1

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

事件监听器检查任何用户活动,并在发生这种情况时重置超时。我希望计时器仅在用户登录时运行,并且一旦超时达到零,它将使用户注销。我通过在人们登录/注销/超时时在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.
jquery if-statement settimeout event-listener
1个回答
0
投票

您绝对应该能够在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);
© www.soinside.com 2019 - 2024. All rights reserved.