0

I was reading about Handling Events in Eloquent JavaScript book, and they had this example, to explain stopPropagation:

let para = document.querySelector('p');
let button = document.querySelector('button');

para.addEventListener('mousedown', () => {
  console.log("Handler for paragraph.");
})
button.addEventListener('mousedown', event => {
  console.log("Handler for button.");
  if (event.button == 2) event.stopPropagation();
})
<p>A paragraph with a <button>button</button>.</p>

I couldn't get why, when they added event listener to para variable they were writing it with () =>

para.addEventListener('mousedown', () => {})

And when they were adding it to the button variable, they were writing it as event =>

button.addEventListener('mousedown', event => {})

I've tried adding the () => to the button variable, and the code works just as it did with event =>. Is this just so we could remember both uses? Or is there a valid reason for this that I'm just missing?

Thanks!

hemoglobin
  • 761
  • 4
  • 12
  • 33

1 Answers1

1

I couldn't get why, when they added event listener to para variable they were writing it with () =>

Event handlers get passed an Event object as their first argument. Since the function didn't use it, it didn't capture it in the arguments list.

And when they were adding it to the button variable, they were writing it as event =>

That function did use the Event object, so it was captured in the argument list.

've tried adding the () => to the button variable, and the code works just as it did with event =>. Is this just so we could remember both uses? Or is there a valid reason for this that I'm just missing?

Now you are using the global event object which MDN says:

You should avoid using this property in new code, and should instead use the Event passed into the event handler function. This property is not universally supported and even when supported introduces potential fragility to your code.

Quentin
  • 914,110
  • 126
  • 1,211
  • 1,335