0
0
Node.jsframework~30 mins

Custom event emitter classes in Node.js - Mini Project: Build & Apply

Choose your learning style9 modes available
Custom Event Emitter Classes in Node.js
📖 Scenario: You are building a simple notification system in Node.js. You want to create your own event emitter class to handle custom events like 'message' and 'error'. This will help you understand how events work behind the scenes.
🎯 Goal: Build a custom event emitter class that can register event listeners and emit events with data. You will create an instance, add listeners, and emit events to see how your class handles them.
📋 What You'll Learn
Create a class called MyEmitter with a constructor that initializes an empty object to store events.
Add a method called on that takes an eventName and a callback function, and stores the callback in the events object.
Add a method called emit that takes an eventName and optional arguments, and calls all callbacks registered for that event with those arguments.
Create an instance of MyEmitter, register at least one listener for the 'message' event, and emit the 'message' event with a string.
💡 Why This Matters
🌍 Real World
Custom event emitters are useful in Node.js to handle asynchronous events like user actions, data loading, or system signals in a clean and organized way.
💼 Career
Understanding how to build and use event emitters is important for backend developers working with Node.js, as it helps in creating scalable and maintainable applications.
Progress0 / 4 steps
1
Create the event storage in the class
Create a class called MyEmitter with a constructor that initializes an empty object called events to store event listeners.
Node.js
Need a hint?

Think of events as a place to keep all your event names and their listeners.

2
Add the on method to register listeners
Add a method called on to the MyEmitter class. It should take eventName and callback parameters. Inside, check if this.events[eventName] exists; if not, set it to an empty array. Then push the callback into this.events[eventName].
Node.js
Need a hint?

This method lets you add functions that run when an event happens.

3
Add the emit method to trigger events
Add a method called emit to the MyEmitter class. It should take eventName and any number of additional arguments using rest syntax. Inside, check if this.events[eventName] exists. If yes, loop over each callback in this.events[eventName] and call it with the additional arguments.
Node.js
Need a hint?

This method runs all functions registered for an event, passing them any data you give.

4
Create an instance, add a listener, and emit an event
Create a variable called emitter and set it to a new instance of MyEmitter. Use emitter.on to add a listener for the 'message' event that takes one argument text and logs it. Then call emitter.emit with 'message' and the string 'Hello, world!'.
Node.js
Need a hint?

This step shows how to use your class to listen and respond to events.