I'm trying to understand how the "event" object is passed and recovered between functions. It was my understanding that event is passed by default as an argument and after seeing the example below it's confusing me even more how this works. How "...args" is getting the event object?
const MyInput = document.querySelector('input');
const checkActivity=(f1)=>{
return (...args)=>{
console.log(args);
f1(args);
};
}
const MyFunc=(e)=>{
console.log(e);
};
MyInput.addEventListener('input',checkActivity(MyFunc));
CodePudding user response:
Here, checkActivity(MyFunc)
is being executed before adding the event listener and not used as a callback. It's the result of this call that is used as a callback. Callback that accepts (...args) possibly an event.
CodePudding user response:
How "...args" is getting the event object?
Let's take that last line of code and possibly make it a bit clearer:
const inputHandler = checkActivity(MyFunc);
MyInput.addEventListener('input', inputHandler);
checkActivity
creates a function that it returns, which I've called inputHandler
above. That function is:
(...args) => {
console.log(args);
f1(args);
};
The ...args
in the parameter list of the function is a rest parameter. It says "take all the arguments this function was called with and gather them up into an array." So args
is an array of the arguments the function was called with.
A function attached as an event listener with addEventListener
like inputHandler
is gets called with just one argument: the event object for the event. So in inputHandler
, args[0]
is the event object.