The Downside to addEventListener Versus onClick Property
I understand the difference between an addE开发者_Python百科ventListener
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?
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.
精彩评论