简体   繁体   English

下划线与争论的辩论

[英]Underscore debounce with arguments

Suppose I have this event handler: 假设我有这个事件处理程序:

var mousewheel = function (e) { /* blah */ };

But, I want to debounce it. 但是,我想辩论它。 So I do this, which works as expected: 所以我这样做,按预期工作:

var mousewheelDebounced = _.debounce(mousewheel, 500);
$(document).on("mousewheel", function (e) {
  e.preventDefault();
  mousewheelDebounced(e);
}

But this doesn't work as expected : 但这不能按预期工作

$(document).on("mousewheel", function (e) {
  e.preventDefault();
  _.debounce(mousewheel, 500)(e);
}

I prefer the compactness of the second form. 我更喜欢第二种形式的紧凑性。 But no debouncing occurs. 但是没有发生去抖动。

I assume no reference to the mousewheelDebounced remains, so the underlying handler is called every time. 我假设没有引用mousewheelDebounced ,所以每次调用底层处理程序。 Is that the reason? 这是什么原因? How can I clean up this code, if possible? 如果可能,我该如何清理此代码?

You can see a fiddle here . 你可以在这里看到一个小提琴

On each mousewheel event (which occurs very often) you create a new version of debounce function. 在每个mousewheel事件(经常发生)上,您将创建一个新版本的debounce功能。 This function has no history, and doesn't know that on previous event there was another one created. 此函数没有历史记录,并且不知道在之前的事件中还创建了另一个。 So it just runs. 所以它只是运行。 That's why you should go with the first version. 这就是你应该使用第一个版本的原因。

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

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