-
Notifications
You must be signed in to change notification settings - Fork 0
/
isolated-event-bus.ts
96 lines (78 loc) · 2.17 KB
/
isolated-event-bus.ts
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
import type { CustomEvent, IEvent } from "@dimkl/events";
import { dispatch, on } from "@dimkl/events";
import { EventBus } from "@dimkl/events";
declare global {
interface PersonGetFullName extends IEvent {
type: "person:getFullName"
data?: any
}
interface PersonSayAloha extends IEvent {
type: "person:sayAloha"
data?: any
}
interface PersonAsyncGetFullName extends IEvent {
type: "person:asyncGetFullName"
data?: any
}
interface Events {
"person:getFullName": PersonGetFullName
"person:sayAloha": PersonSayAloha
"person:asyncGetFullName": PersonAsyncGetFullName
}
}
//
// Definition example
//
const eventBus = new EventBus();
class IsolatedPerson {
public firstName: string;
public lastName: string;
constructor(firstName: string, lastName: string) {
this.firstName = firstName;
this.lastName = lastName;
}
@dispatch({ eventName: "person:getFullName", eventBus })
getFullName() {
return `Isolated ${this.firstName} ${this.lastName}`;
}
@dispatch({ eventName: "person:sayAloha", eventBus })
sayAloha() {
console.log("Isolated said: ", this.aloha());
}
@dispatch({ eventName: "person:asyncGetFullName", eventBus })
async asyncGetFullName() {
return `Isolated ${this.firstName} ${this.lastName}`;
}
aloha() {
return "Aloha to all";
}
}
class IsolatedPersonHandler {
@on({ eventName: "person:getFullName", eventBus })
static handleGetFullName(event: CustomEvent) {
console.log(
"IsolatedPersonHandler: event listener for getFullName: ",
event.data
);
}
@on({ eventName: "person:sayAloha", eventBus })
static handleSayAloha(event: CustomEvent) {
console.log(
"IsolatedPersonHandler: event listener for sayAloha: ",
event.data
);
}
@on({ eventName: "person:asyncGetFullName", eventBus })
static handleAsyncGetFullName(event: CustomEvent) {
console.log(
"IsolatedPersonHandler: event listener for asyncGetFullName: ",
event.data
);
}
}
console.log(`
---- Isolated event bus example ----
`);
const p = new IsolatedPerson("Firstname", "Lastname");
p.asyncGetFullName();
console.log("log getFullName(): ", p.getFullName());