Underscore debounce with arguments

扶醉桌前 提交于 2019-12-23 14:54:12

问题


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. Is that the reason? How can I clean up this code, if possible?

You can see a fiddle here.


回答1:


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.



来源:https://stackoverflow.com/questions/26337905/underscore-debounce-with-arguments

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!