How to hang an event handler?

Why this method doesn't work:

element = document.querySelector('#button'); 
 element.addEventListener( "click" , myFunc('arg') );


and this works:
element = document.querySelector('#button'); 
 element.addEventListener( "click" , function () { myFunc('arg') });


Where is the logic?
March 19th 20 at 08:30
2 answers
March 19th 20 at 08:32
Solution
Because in the first case you pass the return value of the function and the second function to be executed.
i.e. element.addEventListener expects the second argument to the function you want to perform. This piece
myFunc('arg')
this is a function call with the argument 'arg', the function call will be made immediately, and the result (which will be given by the return statement of the function) will be passed in element.addEventListener. Of course you can return myFunc function, then it will work.
you can also write
element.addEventListener( "click" , myFunc.bind(null, 'arg') );

the bind method creates and returns a wrapper function, which when called, it will be filled with argument 'arg'.
March 19th 20 at 08:34
Because you need to pass the function itself - element.addEventListener('click', myFunc) and not to run it. Sending myFunc('arg') you immediately start the execution of the function. To send the function parameters to the handler you want to bind the context .bind, as you wrote in the example above, or use the method .handleEvent interface EventListener:
function myFunc(event) {
console.log(this.arg);
}
.....
element.addEventListener('click', {
 handleEvent: myFunc
 arg: 'arg_value'
});

Find more questions by tags JavaScript