JavaScript Event Listeners vs Event Handlers

风格不统一 提交于 2019-11-28 06:32:57

addEventListener adds an event handler function to the event. There can be an unlimited number of event handlers this way.

Setting onxxxxx sets the event handler to that one function.

From the Mozilla Developer central:

addEventListener registers a single event listener on a single target. The event target may be a single node in a document, the document itself, a window, or an XMLHttpRequest.

To register more than one event listeners for the target, call addEventListener for the same target but with different event types or capture parameters.

And see this chapter of the same document for a comparison of the old onxxxx way.

Since ECMA script is so flexible in its core - allowing to assign functions, methods... virtually everything... to a variable, having an additional functionality to attach a function to a variable such as "addEventListener" is my all means bad design.

So if you ask me, I'll tell you all that Pekka told, which I agree completely, and also that:

pixels.onkeydown = updateNode;

is ECMA script language natural statement, and:

pixels.addEventListener("keydown", updateNode, true);

is overdone DOM supplement that unnecessary confuses many developers making them think what will happen if you set it once the first way, and some other script later potentially may set it using the other way :)

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!