0
0
NestJSframework~10 mins

Event handling in NestJS - Step-by-Step Execution

Choose your learning style9 modes available
Concept Flow - Event handling
Event Occurs
Event Emitter emits event
Event Listener catches event
Listener executes handler function
Handler processes event data
Optional: Emit another event or update state
End
This flow shows how an event is emitted, caught by a listener, and handled step-by-step in NestJS.
Execution Sample
NestJS
import { Injectable } from '@nestjs/common';
import { EventEmitter2, OnEvent } from '@nestjs/event-emitter';

@Injectable()
export class MyService {
  constructor(private eventEmitter: EventEmitter2) {}

  triggerEvent() {
    this.eventEmitter.emit('user.created', { id: 1, name: 'Anna' });
  }

  @OnEvent('user.created')
  handleUserCreatedEvent(payload: { id: number; name: string }) {
    console.log(`User created: ${payload.name}`);
  }
}
This code emits a 'user.created' event and listens for it to log the user's name.
Execution Table
StepActionEvent NamePayloadListener CalledHandler Output
1Call triggerEvent()No
2Emit eventuser.created{ id: 1, name: 'Anna' }No
3Event caught by listeneruser.created{ id: 1, name: 'Anna' }Yes
4Handler executesuser.created{ id: 1, name: 'Anna' }YesUser created: Anna
5Event handling completeNo
💡 Event emitted and handled successfully, no more listeners.
Variable Tracker
VariableStartAfter Step 2After Step 3After Step 4Final
eventEmitterEventEmitter2 instanceEmitted 'user.created'Event caughtHandler processed payloadIdle
payloadundefined{ id: 1, name: 'Anna' }{ id: 1, name: 'Anna' }{ id: 1, name: 'Anna' }undefined
Key Moments - 3 Insights
Why doesn't the handler run before the event is emitted?
The handler only runs after the eventEmitter emits the event, as shown in steps 2 and 3 of the execution_table.
Can multiple listeners handle the same event?
Yes, multiple listeners can subscribe to the same event name and all will run when the event is emitted.
What happens if no listener is registered for an event?
The event is emitted but no handler runs, so no output or side effects occur.
Visual Quiz - 3 Questions
Test your understanding
Look at the execution_table, at which step does the event listener catch the event?
AStep 2
BStep 3
CStep 4
DStep 1
💡 Hint
Check the 'Listener Called' column in the execution_table.
What is the handler output when the 'user.created' event is handled?
ANo output
BUser created: id 1
CUser created: Anna
DError thrown
💡 Hint
Look at the 'Handler Output' column in step 4 of the execution_table.
If the eventEmitter.emit call is removed, what happens in the execution_table?
AListener never called, no handler output
BListener called anyway
CHandler runs with empty payload
DError occurs
💡 Hint
Refer to the flow: event must be emitted to trigger listeners.
Concept Snapshot
NestJS Event Handling:
- Use EventEmitter2 to emit events.
- Decorate methods with @OnEvent('event.name') to listen.
- Emitting triggers all listeners for that event.
- Handlers receive event payloads.
- Useful for decoupling parts of your app.
Full Transcript
In NestJS, event handling works by emitting events using EventEmitter2. When an event is emitted, all listeners registered with @OnEvent for that event name catch it and run their handler functions. The handler receives the event payload and can process it, such as logging or triggering other actions. This flow allows different parts of the app to communicate without tight connections. The execution table shows the steps: calling the triggerEvent method emits the event, the listener catches it, and the handler logs the user name. Variables like eventEmitter and payload change state as the event flows through the system. Beginners often wonder why handlers don't run before emitting or what happens if no listeners exist. The visual quiz tests understanding of when listeners run and what outputs occur. This event pattern helps keep code organized and reactive.