事件处理程序和事件监听器之间有什么区别?
直到最近我还认为它们是同一事物的不同名称:事件发生时调用的函数。但我最近读到一些内容,将事件处理程序称为事件监听器绑定(bind)到的 DOM 元素,这是有道理的。
最佳答案
完全清楚,语言本身没有事件的概念。这些是 DOM 的一部分。
Event Handler: An asynchronous callback that is invoked when an event is raised. Event Listener: An object that implements an interface and has events "pushed" to it.
In the context of DOM events the interface used is this:
interface EventListener {
void handleEvent(in Event evt);
};
然后你像这样注册一个监听器:
target.addEventListener(type, listener, useCapture);
这是来自 MDC 的文档:
listener: The object that receives a notification when an event of the specified type occurs. This must be an object implementing the EventListener interface, or simply a JavaScript function.
因此看起来函数对象隐式实现了 EventListener 以便于使用。
类比
将事件处理程序 视为给 postman 的指令。
I don't want to have to wait for you to stop by so I want you to give the package to my spouse so they can open it.
将事件监听器想象成等着看医生。
I will be listening for a notification that you are ready to see me. Until then I'll be reading a magazine.
归根结底,这些只是
的抽象Hey, I want you to execute this code!
资源
关于JavaScript 事件术语,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3388295/