-
Notifications
You must be signed in to change notification settings - Fork 0
/
event-emitter.html
57 lines (50 loc) · 1.48 KB
/
event-emitter.html
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
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<script src="currency-converter.js"></script>
<title>Document</title>
</head>
<body>
<currency-converter></currency-converter>
</body>
<script>
const converterComponent =
document.getElementsByTagName("currency-converter")[0];
class EventEmitter {
on(event, listener) {
if (!this.listeners) {
this.listeners = {};
}
if (!this.listeners[event]) {
this.listeners[event] = [];
}
this.listeners[event].push(listener);
}
emit(event, arg) {
this.listeners[event].forEach((listener) => listener(arg));
}
}
// Your component starts here
let data = { amount: 1, rate: 1.81 };
let emitter = new EventEmitter();
emitter.on("dataChange", (data) => {
updateResult();
});
updateResult();
converterComponent.onRateUpdateCallback = () => {
data.rate = (1.8 + Math.random() / 10).toFixed(2);
emitter.emit("dataChange", data);
};
converterComponent.onAmountInputCallback = (value) => {
data.amount = value;
emitter.emit("dataChange", data);
};
function updateResult() {
converterComponent.inputInnerHtml = data.amount;
converterComponent.rateInnerHtml = data.rate;
converterComponent.resultInnerHtml = data.amount * data.rate;
}
</script>
</html>