[英]How to pre-fill function arguments?
我有一個附加事件偵聽器的模塊,例如:
document.getElementById('btn').addEventListener('click', handleClick));
但是,當調用handleClick
function 時,我想自動預填充 arguments 與身份驗證令牌(如果存在)。 所以,我有一個withAuth
function 執行以下操作:
const token = 'token'; const withAuth = (fn) => { return (...args) => { console.log('args is ---', [...args, token]); fn.apply(window, [token, ...args]); } } const handleClick = (...args) => { console.log('handle click called----', args); } document.getElementById('btn').addEventListener('click', withAuth((e) => handleClick(e, 'Soham')));
<button id="btn">Click Me</button>
按F12查看控制台output; Stack Overflow 的控制台格式不能很好地處理事件對象
為什么即使第一個控制台正確捕獲了事件 object,我也能夠訪問handleClick
function 中的事件 object? 難道我做錯了什么? 實現此類功能的最佳方法是什么?
withAuth(( e
withAuth((e) => handleClick(e, 'Soham')))
中的 e 沒有收到事件 object,
the event object is passed to the callback function, which is this case, the returned function from withAuth
, so on printing args
there you can see the Event object, then you are calling this passed function (e) => handleClick(e, 'Soham')
通過傳遞一些參數[token, ...args]
,但在 function 中,您只收到第一個參數(e)
,
所以你可以通過(token, event) => handleClick(token, event, 'Soham')
來解決這個問題
或者只是(...args) => handleClick(...args, 'Soham')
const token = 'token'; const withAuth = (fn) => { return (...args) => { console.log('args is ---', [...args, token]); fn.apply(window, [token, ...args]); } } const handleClick = (...args) => { console.log('handle click called----', args); } document.getElementById('btn').addEventListener('click', withAuth((...args) => handleClick(...args, 'Soham')));
<button id="btn">Click Me</button>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.