-
Notifications
You must be signed in to change notification settings - Fork 0
/
PubSub.js
49 lines (39 loc) · 920 Bytes
/
PubSub.js
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
/*
Three thing we can do in pubsub
subscribe
publish
un-subscribe
*/
class PubSub {
constructor(){
this.publisher = {};
}
subscribe(key, value){
if (this.publisher.hasOwnProperty(key))
this.publisher[key].push(value);
else
this.publisher[key] = [value];
}
publish(key, payload) {
if (this.publisher.hasOwnProperty(key)) {
this.publisher[key].forEach((listener) => {
listener(payload);
})
}
}
unsubscribe(key, method) {
if (this.publisher.hasOwnProperty(key)) {
this.publisher[key] = this.publisher[key].filter((item) => item != method)
}
}
}
const printMessage = (msg) =>{
console.log("Listening on " + msg)
}
const printName = (msg) =>{
console.log("Prining Name " + msg)
}
const pubsub = new PubSub();
pubsub.subscribe('message', printMessage);
pubsub.subscribe('message', printName);
pubsub.publish('message', "Ankit")