我得到了这个函数:
const debounce = (func, delay) => {
let inDebounce;
return function() {
const context = this
const args = arguments
clearTimeout(inDebounce)
inDebounce = setTimeout(() => func.apply(context, args), delay)
}
}
var likes_btn = document.getElementsByClassName("js-submit-like");
for (var i = 0; i < likes_btn.length; i++) {
likes_btn[i].addEventListener('click', debounce(function(el) {
alert("hello");
el.preventDefault();
}, 500));
}
所以问题是,我需要在执行去抖动之前使用该.preventDefault()
。目前,真正发生的是在debounce()
结束时执行的,而不是进入函数范围。
如何访问函数范围?谢谢!
只需将其移出去保镖回调:
const debouncer = debounce(() => alert("hello"), 500);
likes_btn[i].addEventListener('click', function(event) {
event.preventDefault();
debouncer(event);
});
对于一些链接函数,这可能会更优雅一些:
const both = (fn1, fn2) => (...args) => (fn1(...args), fn2(...args));
const stop = event => event.preventDefault();
const listen = (el, name, handler) => el.addEventListener(name, handler);
for(const btn of likes_btn) {
listen(btn, "click", both(
debounce(() => alert("hello"), 500),
stop
));
}
创建一个单独的debouncer
回调,侦听器可以关闭该回调:
const debounce = (func, delay) => {
let inDebounce;
return function() {
const context = this
const args = arguments
clearTimeout(inDebounce)
inDebounce = setTimeout(() => func.apply(context, args), delay)
}
}
var likes_btn = document.getElementsByClassName("js-submit-like");
for (let i = 0; i < likes_btn.length; i++) {
const button = likes_btn[i];
const debouncer = debounce((e) => console.log("Hello", button), 500); // you can also use e.target to refer to the button
button.addEventListener('click', function(e) {
console.log("clicked");
debouncer(e);
e.preventDefault();
});
}
<a class="js-submit-like" href="http://www.facebook.com/">Like</a>
<a class="js-submit-like" href="http://www.facebook.com/">Like 2</a>