首页 > 解决方案 > 使用需要作为按钮属性的参数的函数来限制按钮单击 - Javascript

问题描述

努力把我的头缠在这个周围。我刚刚深入研究了节流、关闭和避免全局变量的世界。

我有多个按钮:

<a content_name="home" class="menuLink"><span>HOME</span></a>

我想限制每个按钮的点击,直到 getContent 完成(为了这个问题,我们假设它需要 200 毫秒)。

我的JavaScript:

function getContent(contentName) {
   //Does some things
}

// Simply throttle function

function throttle(callback, limit) {
    var throttleLock = false;
    console.log('throttling: ' + throttleLock);
    return function () {                
        if (!throttleLock) {            
            callback.call();            
            throttleLock = true;        
            setTimeout(function () {    
                throttleLock = false;   
            }, limit);
        }
    }
};

// Event listeners for the buttons

var menuButtons = document.getElementsByClassName("menuLink"); 

var menuBtnClick = function() {
    var attribute = this.getAttribute('content_name');
    getContent(attribute);
};

for (var i = 0; i < menuButtons.length; i++) {
    menuButtons[i].addEventListener('click', throttle(menuBtnClick, 500), false);
}

如果我这样重构(没有节流功能)一切正常,除了它不节流(显然):

for (var i = 0; i < menuButtons.length; i++) {
    menuButtons[i].addEventListener('click', menuBtnClick, 200), false);
}

日志错误是:

Uncaught TypeError: this.getAttribute is not a function
    at menuBtnClick ([this is my filename and line])
    at HTMLAnchorElement.<anonymous> ([this is my filename and line])

我知道油门函数正在触发(控制台日志),但它似乎没有触发回调,并且throttleLock 的值仍然为假。

请帮忙,我确定我做错了什么,我想学习。如果有任何替代这种尝试的方法,请开火,我全神贯注。

谢谢。

标签: javascriptperformanceclosuresaddeventlistenerthrottling

解决方案


只需将上下文应用于回调调用:

callback.call(this);   

这是示例: https ://jsbin.com/yekimaqelo/1/edit?html,js,console,output


推荐阅读