-
Notifications
You must be signed in to change notification settings - Fork 0
/
index-emitter.js
96 lines (75 loc) · 2.66 KB
/
index-emitter.js
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
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
const EventEmitter = require("events").EventEmitter; // package event
const ShoppingList = require("./scripts/events/ShoppingList");
const programmer = new EventEmitter(); // constructor
let energy = 5;
let insomniaRisk = 0;
// Handler
/* We create a custom event and associate callback to the ".on" method */
programmer.on("drinkCoffee", function () {
console.log("Boost");
});
// we can create several custom events with the same name
programmer.on("drinkCoffee", function (coffee = "black coffee") {
console.log(`Energy increase after drinking ${coffee}: ${++energy}`);
});
const increaseInsomnia = () => {
insomniaRisk++;
console.log(`Insomnia risk raised to level: ${++insomniaRisk}`);
};
programmer.on("drinkCoffee", increaseInsomnia);
// programmer.on("drinkCoffee", function () {
// console.log(`Insomnia risk: ${++insomniaRisk}`);
// });
// Emitter
programmer.emit("drinkCoffee");
programmer.emit("drinkCoffee", "brazilian coffee");
programmer.emit("drinkCoffee");
console.log("--------");
// Handler using class that inherits Emitter
const myShoppingList = new ShoppingList();
myShoppingList.on("added", (list) => {
console.log(`Total list: ${list}`);
});
// If "frozen", the event "bringFreezerBag" is emitted:
// myShoppingList.on("bringFreezerBag", (list) => {
// console.log(`Warning: ${list}`);
// });
// We can use the method ".once" so the event will be launched only once
myShoppingList.once("bringFreezerBag", (list) => {
console.log(`Warning: ${list}`);
});
// We manage the error
myShoppingList.once("error", (error) => {
console.log(`${error}`);
});
myShoppingList.add("camembert");
myShoppingList.add("frozen vegetables");
myShoppingList.add("frozen fishes");
myShoppingList.add("computer");
myShoppingList.add("chocolate");
// Functions that return an event emitter
console.log("--------");
const getBook = () => {
const ee = new EventEmitter();
/* we instruct the engine to invoke this function at the end of the current operation,
before the next event loop tick starts */
// process.nextTick(() => {
// ee.emit("searchbookStarted");
// });
setImmediate(() => {
ee.emit("searchbookStarted");
});
const searchDuration = Math.floor(Math.random() * 5 * 1000);
setTimeout(() => {
const book = { title: "Book title", author: "Author of the book" };
ee.emit("bookFound", book);
}, searchDuration);
return ee;
};
const desiredBook = getBook();
desiredBook.on("searchbookStarted", () => {
console.log("Book search has begun!");
});
desiredBook.on("bookFound", (data) => {
console.log(`Book found: ${JSON.stringify(data)}`);
});