event emitter
# Node.js
const EventEmitter = require("events");
class MyEmitter extends EventEmitter {}
const myEmitter = new MyEmitter();
myEmitter.on("my-event", (msg) => {
console.log(msg);
});
myEmitter.on("my-other-event", (msg) => {
console.log(msg);
});
myEmitter.emit("my-event", "hello world");
myEmitter.emit("my-other-event", "hello other world");
1
2
3
4
5
6
7
8
9
10
11
12
13
14
2
3
4
5
6
7
8
9
10
11
12
13
14
Output
hello world
hello other world
1
2
2
# Go
(closest thing is to use channels)
package main
import (
"fmt"
)
type MyEmitter map[string]chan string
func main() {
myEmitter := MyEmitter{}
myEmitter["my-event"] = make(chan string)
myEmitter["my-other-event"] = make(chan string)
go func() {
for {
select {
case msg := <-myEmitter["my-event"]:
fmt.Println(msg)
case msg := <-myEmitter["my-other-event"]:
fmt.Println(msg)
}
}
}()
myEmitter["my-event"] <- "hello world"
myEmitter["my-other-event"] <- "hello other world"
}
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
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
Output
hello world
hello other world
1
2
2
编辑 (opens new window)
上次更新: 2022/09/30, 11:34:22