繁体   English   中英

在JS中具有多个参数的函数中访问对象范围

[英]Acces to object scope in a function with multiple params in JS

我得到了这个功能:

 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()的末尾执行,而不是在函数范围内执行。

如何进入功能范围? 谢谢!

只需将其移到debouncer回调之外即可:

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> 

暂无
暂无

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

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