DEV Community


Posted on

What is an event emmitter?

I recently did a Pramp interview where I was asked to create an event emitter. After reading several sources, it's still not clicking.

In basic words, what is or is not an event emitter? When would you want to create one? How is different from an event listener?

Top comments (5)

papayankey profile image
Benneth Yankey • Edited
  • What is it?
    EventEmitter is an event system for NodeJS environment. It implements publish-subscribe pattern: subscribers can listen to events and take action whilst publishers emit or execute the events.

  • How is it different from EventListener?
    They are very similar but not the same. EventListener lives in the browser whilst EventEmitter lives outside the browser.

  • How do you create one?

require it on events object

const EventEmitter = require('events').EventEmitter

create emitter (publisher)

const newsPaperEmitter = new EventEmitter()

create subscriber(s)

function getNewsPaper(news) {

attach subscriber to publisher

newsPaperEmitter.on('newsPaper', getNewsPaper)

publish news paper

newsPaperEmitter.emit('newsPaper', 'news on event emitter')
  • use case is centralized logging.
augustocb23 profile image
Augusto César • Edited

It's a part of the Observer design pattern. A Subject (or Event Emitter) emits events to its subscribers, and this subscribers can do something when this event occurs.

There are several implementations of this pattern. RxJS is a famous implementation for Javascript/Typescript, used by React and Angular.
In C# there's a native implementation that uses the EventHandler class.

dragosnedelcu profile image
Dragos Nedelcu

Fantastic add, thanks for the Wikipedia link and the implementation agnostic answer.

A quick tip: "his" => "its"
hehe no need for gender on this one :)

augustocb23 profile image
Augusto César

Ops 😬

jwp profile image
John Peters • Edited

Prior to Observables, the 'event' was a way to send a message. Being time independent, no 'event listeners' knew when the message would arrive. The program would be interrupted as soon as the message arrived. The message was 'emitted' for the listeners to receive.

Observables took the same pattern but added many more helper functions