[英]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.