【问题标题】:How can I use throttling with getting an event target?如何使用节流来获取事件目标?
【发布时间】:2019-06-06 02:14:32
【问题描述】:

通过参考本网站, https://codeburst.io/throttling-and-debouncing-in-javascript-646d076d0a44

throttled(delay, fn) {
    let lastCall = 0;
    return function (...args) {
        const now = (new Date).getTime();
        if (now - lastCall < delay) {
            return;
        }
        lastCall = now;
        return fn(...args);
    }
}


我想使用这样的节流功能。

item.addEventListener('click', throttled(2000, func(e.target)));


我必须使用它来获取 e.target 的值。
但是,如果您编写此代码,则节流功能将无法正常工作。

item.addEventListener('click', (e) => {throttled(2000, func(e.target))});


如何在获取有针对性的点击事件时让节流功能正常工作?

【问题讨论】:

    标签: javascript events ecmascript-6 throttling


    【解决方案1】:

    您的throttled 函数将返回一个围绕原始事件处理程序的包装函数。它会将在now - lastCall &gt;= delay 时收到的任何参数传递给fn 回调函数。
    这是您将作为事件处理程序添加的包装函数,即throttled() 的返回值。

    所以您需要传递给throttled 的只是一个普通的事件处理程序,即您将传递给事件侦听器的相同:

    // let's be a bit verbose
    
    // our event handler
    function handleevent(evt) {
      console.log(evt.clientX); // logging the clientX here because evt.target is a big object for SO's console.
    }
    // the wrapper function
    const myThrottledFunc = throttled(2000, handleevent);
    // we add the wrapper as event handler
    addEventListener('click', myThrottledFunc);
    
    
    function throttled(delay, fn) {
      let lastCall = 0;
      return function wrapper(...args) {
        const now = (new Date).getTime();
        if (now - lastCall < delay) {
          return;
        }
        lastCall = now;
        return fn(...args);
      }
    }
    click anywhere

    或作为单线onclick = throttled(2000, evt =&gt; console.log(evt.target));

    【讨论】:

    • 您好,请您解释一下或参考一些文档,为什么 function throttled(delay, fn) { let lastCall = 0; 不重新初始化 lastCall to 0 这太神奇了
    • @BlackMamba 确实如此,但 throttled 在我们第一次初始化包装函数时只被调用一次。被多次调用的是包装器,但这个永远不会将 lastCall 设置为 0。
    • 哦,好的,我现在知道了
    【解决方案2】:

    您的节流函数需要一个函数作为第二个参数。

    假设 func 只是将e.target 记录到控制台,你可以这样写:

    item.addEventListener('click', throttled(2000, func));
    

    const func = (e) => console.log(e.target);
    

    或者,如果您希望将所有内容集中在一行中:

    item.addEventListener('click', throttled(2000, (e) => func(e.target)));
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2010-12-13
      • 2015-08-26
      • 2018-01-26
      • 1970-01-01
      • 2020-05-07
      • 2018-08-19
      相关资源
      最近更新 更多