The correct way to pass Methods as Event Handlers in Javascript
Those parentheses make a BIG difference and change the result
One of my colleagues wasn't receiving the expected parameters in a JS method the other day. He was trying to make a third-party Vue.js plugin work in a project (as we all do with fluctuating confidence).
Let's go through a simple example with vanilla Javascript but the rule applies everywhere (including your favorite JS framework).
document.getElementById("just-do-it").addEventListener("click", spreadHappiness());
function spreadHappiness() {
console.log('You are awesome');
}
What do you think will happen when a user clicks on that button?
Guessed it?
Nothing!
The method gets called upon page load and nothing happens when the button is clicked. Hmm...
Did you notice that we have put the parentheses ()
after method name spreadHappiness()
in the first line?
It is that classic call-by-reference vs call-by-value thing.
That line should have been written like this (with parentheses removed):
document.getElementById("just-do-it").addEventListener("click", spreadHappiness);
And with that, clicking on that button would log the statement in the browser console as expected.
Now, did you know that the event handler receives an object based on the Event
interface as a parameter? This means you can use the Event metadata in your method. Like so:
function spreadHappiness(event) {
console.log(event.type); // click
}
So, you should skip those parentheses when passing a method name as an event handler in most cases. When one needs to get the event handler dynamically, calling another method and returning it makes sense.
Closing
In short, putting those parentheses after the method name while specifying the event handler is not an optional thing. It changes the result.
method(): Executed instantly and the return value used as the event handler.
method: Used as the event handler and it receives the parameters when called.
Again, Doing a method call and passing the method reference are two different things and developers, especially beginners, should be aware of this difference.
Do any of your friends need to know this? Share this article with them to make their debugging life easier.