Member-only story
How to Create Your Own Event Emitter in JavaScript
Build a simple event emitter based on ES6 classes
What’s it For?
First of all, for your understanding and knowledge. To get the full picture of how something works, write it yourself.
Secondly, to write cleaner code. We’ll give you a real example.
Last but not least: you might be asked to write your own small and simple EventEmitter
in an interview — it would be nice to be prepared!
Hello World!
Let’s start with the documentation. The Node.js documentation answers all the questions you may have but, like much documentation, it’s a bit complicated. That’s why you may want a quick guide.
Creating
As I mentioned, we’re going to use ES6 Classes.
class MyEventEmitter {}
We need a constructor to initialize our store
for events and callbacks.
constructor() {
this._events = {};
}
Let’s describe our first method, on
. It takes two arguments: the event’s name, and the listener, which will be fired.
From the code above we can see that if the object _events
doesn’t have the property, it creates it and assign an empty array. After that, a new listener will be added to the array. If the property exists, we just add a listener.
The next method is removeListener
. As before, it takes two arguments: the event’s name and the listener, which must be removed.
What is going on here? It’s simple. If we don’t have such an event we throw a new error with the related message. Otherwise, we filter an array of listeners.