Ember:在滚动事件侦听器上多次调用 debounce

Ember : debounce called multiple times on scroll event listener

我在滚动事件侦听器中添加了一个去抖动方法。像这样。

$group.on("scroll.topFix",() => {
   console.log('scroll event');
   debounce(this, ()=> {
     console.log('debounce called);
   },1000);
});

当我在 $group 上滚动时,去抖动也被调用与调用滚动事件的次数相同。不知道这个东西的漏洞在哪里

例如,如果 5 次滚动事件 打印然后 debounce 调用 也被调用 5 次.

这是 ember debounce documentation.

的 link
<script src="https://ajax.aspnetcdn.com/ajax/jQuery/jquery-3.4.0.min.js"></script>
$(window).scroll(function() {
   console.log('scroll event');
   debounce(this, ()=> {
     console.log('debounce called');
   },1000);
})

这种方法对我有用...

$group.on("scroll.topFix",() => {
  console.log('scroll event');
  debounce(this, scrollfunction},1000);
});

let scrollfunction = () => {
   console.log('debounce called);
};

scroll event同时触发4次时debounce called只调用一次

你的问题是你传递了一个匿名函数给debounce:

debounce(this, ()=> {
  console.log('debounce called);
},1000);

这是有问题的,因为您每次 debounce 时都需要重新创建此函数 !所以你永远不会用同一个函数调用 debounce 两次,这是它执行不同于 setTimeout.

的任何事情所必需的

所以你应该create/save这个函数到某个地方然后像

一样调用它
debounce(this, this.doSomething, 1000);

确保您始终传递完全相同的函数。仅仅因为 2 个函数做同样的事情并不意味着它是相同的函数实例。