带参数的下划线去抖动 [英] 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);
}
但是这不符合预期:
$(document).on("mousewheel", function (e) {
e.preventDefault();
_.debounce(mousewheel, 500)(e);
}
我更喜欢第二种形式的紧凑性.但是不会发生反跳.
I prefer the compactness of the second form. But no debouncing occurs.
我假定没有对mousewheelDebounced
的引用,因此每次都调用底层处理程序.那是原因吗?如果可能的话,我该如何清理此代码?
I assume no reference to the mousewheelDebounced
remains, so the underlying handler is called every time. Is that the reason? How can I clean up this code, if possible?
您可以在此处看到 小提琴 .
You can see a fiddle here.
推荐答案
在每个mousewheel
事件(此事件经常发生)上,您将创建debounce
函数的新版本.此函数没有历史记录,并且不知道在先前的事件中还创建了另一个函数.这样就可以运行了.这就是为什么您应该使用第一个版本.
On each mousewheel
event (which occurs very often) you create a new version of debounce
function. 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.
这篇关于带参数的下划线去抖动的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!