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
One small tradeoff: wrapping with () => save() also delays it, but it creates a new function and can change this, so pass save directly unless you need extra args.
BobaMilk
Because addEventListener stores a callback for later, save() fires during setup while save waits for the click, though one edge case is methods like obj.save may still need binding if they rely on this.
Sora
Another way to picture it is addEventListener wants a phone number, while save() is you already making the call, and for obj.save you may need obj.save.bind(obj) if this matters.
Quelly
save() runs immediately because the parentheses invoke it right there.
WaffleFries
One quick check is to console.log(save()) versus console.log(save) in setup and you will see the first evaluates now while the second is just a function value, though methods still bite if this is involved.
Sarah ![]()
The immediate giveaway is the return value: if you pass save() into the click handler, the listener gets whatever save returned, not the function itself, so the bug shows up before the first click.
Yoshiii
:: Copyright KIRUPA 2024 //--