Consider this snippet.
button.addEventListener('click', save());
Why does save run right away, and what is the correct version.
Hari
Consider this snippet.
button.addEventListener('click', save());
Why does save run right away, and what is the correct version.
Hari
Because save() calls the function immediately and passes its return value to addEventListener.
Sora
Pass the function reference, not the result, so use button.addEventListener('click', save) unless you deliberately want save('draft'), in which case wrap it like () => save('draft').
Arthur
It runs now because the parentheses invoke save during setup, and the only wrinkle is if save returns another function then that returned function becomes the handler.
Hari
save() executes while the listener is being registered, so the browser gets whatever it returns instead of a callback.
BayMax
:: Copyright KIRUPA 2024 //--