-
Notifications
You must be signed in to change notification settings - Fork 33
/
pubsub.ats
67 lines (55 loc) · 1.42 KB
/
pubsub.ats
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
import { Logger } from '../logger';
export class Provider {
constructor() {
this.msgQueue = []
this.subscribers = {}
}
notify(msg:string) {
this.msgQueue.push(msg)
}
subscribe(msg:string, subscriber:Subscriber) {
if (!(msg in this.subscribers)) {
this.subscribers[msg] = [];
}
this.subscribers[msg].push(subscriber);
}
unsubscribe(msg:string, subscriber:Subscriber) {
var subscribers = this.subscribers[msg];
var index = subscribers.indexOf(subscriber);
if (index > -1) {
subscribers.splice(index, 1);
}
}
update() {
var _that = this;
this.msgQueue.forEach(msg=> {
if (msg in this.subscribers) {
_that.subscribers[msg].forEach(sub=> {
sub.run(msg)
});
}
});
this.msgQueue = []
}
}
export class Publisher {
constructor(msgCenter:Provider) {
this.provider = msgCenter;
}
publish(msg:string) {
this.provider.notify(msg)
}
}
export class Subscriber {
constructor(name:string, msgCenter:Provider) {
this.name = name;
this.provider = msgCenter;
this.logger = new Logger();
}
subscribe(msg:string) {
this.provider.subscribe(msg, this);
}
run(msg:string) {
this.logger.log(this.name + " & " + msg);
}
}