简体   繁体   English

JS:我正在尝试理解事件发射器与事件侦听器

[英]JS: I am trying to understand event emitters vs event listeners

I am trying to understand the difference between event handlers and event emitters. 我试图理解事件处理程序和事件发射器之间的区别。 I understand event listeners and how to attach them, for example, the following: 我理解事件监听器以及如何附加它们,例如,以下内容:

let element = document.getElementById('test-id');

element.addEventListener('click', handleClick)
})

function handleClick() {
    console.log("is this function considered an event handler?")
}

But even after reading about event emitters and handlers, I don't know exactly how or where they come into play. 但即使在阅读了事件发射器和处理程序之后,我也不确切知道它们是如何发挥作用的。

you can call the emit() method whenever you need, passing the name of the event and any number of arguments. 你可以随时调用emit()方法,传递事件的名称和任意数量的参数。 For example: 例如:

const EventEmitter = require( 'events' );
class MyClass extends EventEmitter {
    doSomething() {
        // do something...
        if ( !err )
            this.emit( 'success', result );
        else
            this.emit( 'error', err );
    }
}

You can find the full API documentation of the EventEmitter class here . 您可以在此处找到EventEmitter类的完整API文档。

Refer here also What is an "event emitter"? 请参阅此处什么是“事件发射器”?

event emitters - code that create event - you write code to create events and then you write handlers for it. 事件发射器 - 创建事件的代码 - 您编写代码来创建事件,然后为其编写处理程序。

event listeners - event is created by browser eg - http request, click- you write code to handle the events that is listeners. 事件监听器 - 事件由浏览器创建,例如 - http请求,单击 - 您编写代码来处理作为监听器的事件。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM