-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathnode5.js
More file actions
36 lines (24 loc) · 767 Bytes
/
Copy pathnode5.js
File metadata and controls
36 lines (24 loc) · 767 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
// Chapter 5 – Events & EventEmitter Example
const EventEmitter = require("events");
const emitter = new EventEmitter();
// 1. Simple Listener
emitter.on("hello", () => {
console.log("Hello Event Triggered!");
});
// Emit the event
emitter.emit("hello");
// 2. Sending Data with Events
emitter.on("userLogged", (username) => {
console.log(`${username} has logged in`);
});
emitter.emit("userLogged", "Mounika");
// 3. Multiple Listeners
emitter.on("start", () => console.log("Start listener 1"));
emitter.on("start", () => console.log("Start listener 2"));
emitter.emit("start");
// 4. Using once()
emitter.once("load", () => {
console.log("Loaded only once!");
});
emitter.emit("load");
emitter.emit("load"); // This will not trigger again