【问题标题】:lodash debounce ignore space keylodash debounce 忽略空格键
【发布时间】:2021-10-06 20:18:10
【问题描述】:

嗨,我正在使用 lodash .. 一切都很好.. 但我有问题,我希望按下回车键时 debouce 不工作.. 这是我的 lodash 钥匙..

search_products:_.debounce(function(event)
{
     // my code here 
    // how can i let debounce work with all keys but not with enter key
},5),

我希望延迟 5ml 不能与 enter 一起使用 另外,如果有任何其他方法,如 debouce 或任何花药库,任何人都可以在这里帮助我 那可能吗 谢谢

【问题讨论】:

    标签: javascript lodash


    【解决方案1】:

    您可以使用flush() method included with lodash debounce

    flush 将立即调用所有延迟的函数调用。

    在下面输入会有1秒的延迟,但按回车会立即记录结果。

    const debounced = _.debounce(value => {
      console.log(value);
    }, 1000);
    
    const handler = event => {
      if (event.key === 'Enter') return debounced.flush();
    
      debounced(event.target.value);
    }
    
    document.querySelector('input').addEventListener('keyup', handler);
    <script src="https://cdn.jsdelivr.net/npm/lodash@4.17.21/lodash.min.js" crossorigin="anonymous" referrerpolicy="no-referrer"></script>
    
    <input type="text" placeholder="type something">

    【讨论】:

      【解决方案2】:

      您可以提取去抖动函数,并仅在按下回车键以外的其他内容时调用它。

      {
        search_products: function (event) {
          if (event.code !== 'Enter') {
            debounced(event);
          }
        }
      }
      
      const debounced = _.debounce(function(event) {
        // ...
      }, 5);
      

      【讨论】:

        猜你喜欢
        • 2018-04-23
        • 1970-01-01
        • 2012-04-22
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2015-05-21
        • 2022-10-25
        相关资源
        最近更新 更多