CodeBlanks Logo Icon CodeBlanks

Summary - Events

Combine EventEmitter, on/emit and once to write a counter app.

Summary - Events

In this group you learned the core tools of EventEmitter: registering listeners with on, firing events with emit, adding one-time listeners with once, removing listeners with removeListener, and handling errors with the error event.

Now you will combine them into a counter application. The app is built on an EventEmitter; each time the "inc" event fires, the counter increases and the current value is printed. This mini task shows how events combine in a real scenario.

Counter design

The skeleton of the counter app: a count variable, an EventEmitter instance, and an "inc" listener. The listener increments count by one and prints the new value. External emit("inc") calls advance the counter.

Flow: const counter = new EventEmitter(); let count = 0; counter.on("inc", () => { count++; console.log("Count: " + count); });. Three emit("inc") calls print Count: 1, Count: 2, Count: 3. The listener closes over count (closure), so the value persists across calls.

Practice Write the counter app

Create an EventEmitter instance named counter. Initialize count to 0. Listen for the "inc" event: the listener increments count by one and prints "Count: " + count. Call emit("inc") three times.

Starter code

index.js
// Import EventEmitter and create a counter instance
// write here

let count = 0;
// Add a listener for the "inc" event: increment count and print "Count: " + count
// write here

// Fire the "inc" event three times
// write here

Sample solution

index.js
const { EventEmitter } = require("events");
const counter = new EventEmitter();
let count = 0;
counter.on("inc", () => { count++; console.log("Count: " + count); });
counter.emit("inc");
counter.emit("inc");
counter.emit("inc");

Expected output

Sayaç: 1
Sayaç: 2
Sayaç: 3

Questions and answers

Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.

1 What pieces does the counter app combine?

index.js
emitter.on("inc", () => { count++; ... })
  • Only console.log
  • EventEmitter, on ve emit Correct answer
  • Only require
  • Only new

Explanation: An EventEmitter instance, on to listen and emit to fire combine.

2 Match each tool to its role

Term Meaning
on("inc", ...) Listens for the counter
emit("inc") Triggers the increment
count++ Increases the value by one
new EventEmitter() Creates the publisher

All lessons in Intermediate