Skip to content
loading...

What is an event emmitter?

jasterix profile image Jasterix twitter logo github logo ・1 min read  

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?

twitter logo DISCUSS (6)
Discussion
markdown guide
 

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.

en.m.wikipedia.org/wiki/Observer_p...

 

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 :)

 
 
  • 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) {
  console.log(news);
}

attach subscriber to publisher

newsPaperEmitter.on('newsPaper', getNewsPaper)

publish news paper

newsPaperEmitter.emit('newsPaper', 'news on event emitter')
  • use case is centralized logging.
 

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

 

Here's a very simple one I wrote some time ago: github.com/smokku/wrte/blob/master...

Maybe this one "clicks"?

Classic DEV Post from Jul 30 '19

PublishTo.Dev: Scheduling article publishing on dev.to

Jasterix profile image
My favorite things are coding, cartoons, and cereal. Find me elsewhere @jasterix or @_jasterix