EVT
Search…
Extending Evt
It is common practice to create classes that extends EventEmitter .
As a general rule of thumb, we tend to avoid inheritance in favor of other patterns but if you want to do it there is how.
1
import { Evt, to } from "evt";
2
3
class MySocket extends Evt<
4
["connect", void] |
5
["disconnect", { cause: "remote" | "local" } ] |
6
["error", Error]
7
> {
8
9
public readonly address: string;
10
11
constructor(
12
params: { 
13
address: string;
14
}
15
) {
16
17
super();
18
19
const { address } = params;
20
21
this.address = address;
22
23
setTimeout(
24
() => this.post(["connect", undefined]),
25
300
26
);
27
28
setTimeout(
29
() => this.post(["disconnect", { "cause": "local" }]),
30
2000
31
);
32
33
}
34
35
}
36
37
38
39
const socket = new MySocket({
40
"address": "wss://example.com"
41
});
42
43
(async ()=> {
44
45
await socket.waitFor(to("connect"));
46
47
console.log("Socket connected");
48
49
})();
50
51
socket.$attach(to("error"), error => { throw error });
52
53
socket.$attach(
54
data=> data[0] === "disconnect" ? [ data[1] ] : null, //Just so you know this is what the to() operator do
55
({ cause })=> console.log(`socket disconnect (${cause})`)
56
);
Copied!
Now we encourage favoring composition over inheritance and having one EVT instance for each events type.
1
import { Evt } from "evt";
2
import type { NonPostableEvt } from "evt";
3
4
class MySocket {
5
6
public readonly address: string;
7
8
/*
9
We use NonPostableEvt instead of Evt so we make clear that
10
the connect disconnect and error events are not supposed to
11
be posted from outside the class implementation.
12
*/
13
14
public readonly evtConnect: NonPostableEvt<void> = new Evt();
15
16
//Equivalent of the line above but it prevent you from having to import the ToNonPostable helper type
17
public readonly evtDisconnect = Evt.asNonPostable(
18
Evt.create<{
19
cause: "local" | "remote"
20
}>()
21
);
22
23
public readonly evtError= Evt.asNonPostable(
24
Evt.create<Error>()
25
);
26
27
constructor(
28
params: { 
29
address: string;
30
}
31
) {
32
33
const { address } = params;
34
35
this.address = address;
36
37
38
setTimeout(
39
() => Evt.asPostable(this.evtConnect).post(),
40
300
41
);
42
43
setTimeout(
44
() => Evt.asPostable(this.evtDisconnect).post({ "cause": "local" }),
45
2000
46
);
47
48
}
49
50
}
51
52
const socket = new MySocket({
53
"address": "wss://example.com"
54
});
55
56
(async ()=> {
57
58
await socket.evtConnect.waitFor();
59
60
console.log("socket connected [bis]");
61
62
})();
63
64
socket.evtError.attach(error => { throw error });
65
66
socket.evtDisconnect.attach(
67
({ cause }) => console.log(`socket disconnect (${cause})`)
68
);
Copied!
Last modified 9mo ago
Copy link