简体   繁体   English

JavaScript的反跳:如何获取e.target?

[英]javascript debounce: how to get e.target?

I'm using the implementation of debounce from https://davidwalsh.name/javascript-debounce-function . 我正在使用https://davidwalsh.name/javascript-debounce-function中的反跳实现。

The question now is: How do I get the event (e.target) from the eventlistener and use it inside the debounced function? 现在的问题是:如何从事件侦听器获取事件(例如目标),并在反跳功能中使用它?

This is what I've come up with: 这是我想出的:

document.querySelector('textarea')
  .addEventListener('input', (e) => {
     debounce(
         () => { console.log('debounce at '+e.target.value); },
         1000,
         false
     )(e); // add (e) so that the function debounce returns gets called inside the anonymous function
  });

The problem is that it triggers immediately (and the debounce effect gets effectively killed). 问题在于它会立即触发(并且去抖动效果会被有效消除)。

you need to wrap the input event handler, like so: 您需要包装输入事件处理程序,如下所示:

function handler(e) {
  console.log('debounce at '+e.target.value); 
}
const debouncedHandler = debounce(handler, 1000)
document.querySelector('textarea').addEventListener('input',debouncedHandler, false)

now when the event fires it will call the same handler and not a new one 现在,当事件触发时,它将调用相同的处理程序,而不是新的处理程序

demo 演示

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM