Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

The Downside to addEventListener Versus onClick Property

I understand the difference between an addEventListener and the onclick property and know how to use both. I am wondering if there is a draw back to always using EventListener's instead of using the onclick property. The EventListener appears to be much more powerful than just using the onclick atleast when dynamically generating the HTML from javascript.

Is there a memory/cpu drawback or am I safe to only use EventListeners?

like image 657
slimbo Avatar asked Oct 17 '25 05:10

slimbo


1 Answers

This probably isn't the direction you were going in, but there are a few instances where you would be unable to remove an event listener.

Event handlers are completely public, and can be modified (to a certain extent) by anyone:

// You do this
myLink.onclick = function () {
    alert('hello, world');
};

// Another developer who hates you because
// he thinks that you're hitting on his girlfriend
// but you're not, you're just friends, but
// he's jealous so he doesn't understand
// does this
myLink.onclick = function () {
    alert('muahahahaha');
};

// Someone else could even get rid of
// the handler entirely:
myLink.onclick = null;

But there is no publically accessible list of event listeners. The only way to remove an event listener is if you still have access to the original function:

myLink.addEventListener('click', function () {
    alert('hello, world');
}, false);

There is now no way to remove that event listener. You gave it an anonymous function, so even you wouldn't be able to remove it if you wanted to.

like image 116
sdleihssirhc Avatar answered Oct 19 '25 18:10

sdleihssirhc



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!