简体   繁体   中英

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. 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 .

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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