Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

destructing ev.preventDefault()

Tags:

javascript

When I attempt to use Object destructuring with ev.preventDefault(), I receive the following error in Chrome:

Uncaught TypeError: Illegal invocation

However, when I use ev.preventDefault() without destructuring, it works fine. Code that reproduces this issue is shown below.

const button = document.getElementById(`test-button`);

button.onclick = ({ preventDefault }) => {
  preventDefault();
};
<button id=test-button type=button>Click me to see the error</button>

Any idea why this is happening? Or how I can use Object destructuring with the Event Object?

like image 522
dwhieb Avatar asked Apr 02 '18 18:04

dwhieb


1 Answers

preventDefault is a method that must be invoked on an event object to know which default to prevent. When you do just preventDefault(), that's not method call syntax and the event object is nowhere to be found: Illegal invocation. Destructuring syntax just accesses the value, it does not automatically bind any functions.

button.onclick = (e) => {
  const { preventDefault } = e; // like const preventDefault = e.preventDefault;
  preventDefault(); // does not work, unlike preventDefalt.call(e)
};
like image 97
Bergi Avatar answered Oct 20 '22 01:10

Bergi