Use Event emitter in Ruby

Vladislav Kopylov
2 min readApr 16, 2019

--

Photo by Nathan Dumlao on Unsplash

What is Event emitter?

Event emitter is so close to the observer pattern. It works the same: something emits an event, another object listens the event and execute the code. Event emitter triggers an event which everyone can listen. Various libraries have different implementation, but the basic idea is a tool for issuing events and subscribing to them.

How to work with it?

There is an simple implementation of code. Just a module that can be included to any class.

Here the easiest example. We implement code that will print the line ‘ring ring ring’, then we create an event and subscribe code to the event.

Where should I use the pattern?

Everywhere when you have subscribing feature. For example: chat application (many users wait up new messages); answers and questions web-sites (many users subscribe to questions); real-time application where people subscribe to updates; notifications about software update.

Here the example of chat app implementation with Event emitter.

Of course, you don’t need to implement it by yourself. There are some great implementations in Github. If you want to have some practice, you could write it from scratch. It is so funny.

--

--

Vladislav Kopylov
Vladislav Kopylov

Responses (1)