Node.js Course
Node.js
/
Intermediate

Custom Events

Definition

Extending the `EventEmitter` class to create custom objects that possess built-in event broadcasting capabilities.

Explain Like I'm New

Instead of creating a standalone 'radio station' (a raw EventEmitter), you make your own custom class INHERIT the radio station's powers. Now, your `UserDatabase` class doesn't just save users; it can natively broadcast `db.emit('userSaved')` directly from within its own methods.

Real World Example

Creating a `ChatRoom` class that extends `EventEmitter`. When a user types a message, the class calls `this.emit('message', text)`, and all connected WebSocket clients instantly receive it.

Common Use Cases

  • •Building complex system architectures
  • •Creating libraries like Socket.io

Interactive Example

Loading...
Console output will appear here...

Interview Questions

basic

  • How do you make a class an EventEmitter?

intermediate

  • Why do we call `super()` inside the constructor?

Flash Cards

Question

How to make a class an EventEmitter?

Click to reveal answer
Answer

By using the ES6 `extends` keyword: `class MyClass extends EventEmitter {}`.

Question

Why call super()?

Click to reveal answer
Answer

Because `MyClass` inherits from `EventEmitter`, calling `super()` executes the `EventEmitter`'s hidden constructor, properly initializing the hidden memory objects needed to store event listeners.