Consider this snippet.
button.addEventListener('click', save());
Why does save run right away, and what is the correct version.
BayMax ![]()
Consider this snippet.
button.addEventListener('click', save());
Why does save run right away, and what is the correct version.
BayMax ![]()
save() calls the function immediately and passes its return value to addEventListener.
MechaPrime ![]()
Use save not save(), because the listener needs a function reference, not the result of calling it, and if you need arguments wrap it like () => save(id).
Sarah ![]()
A quick way to see it is console.log(save()) versus console.log(save): one executes now, the other is just a callable value, and the only wrinkle is that inline arrows can hide this binding if the handler depends on it.
Quelly
Because the browser needs a function to call later, and save() is you calling it during setup.
Arthur
:: Copyright KIRUPA 2024 //--