-
Notifications
You must be signed in to change notification settings - Fork 1
/
AdvancedPubsub.js
91 lines (77 loc) · 2.22 KB
/
AdvancedPubsub.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
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
class Events {
constructor() {
this.subscriptionList = [];
}
subscribe(name, callback) {
if (!this.subscriptionList[name]) {
this.subscriptionList[name] = [];
}
this.subscriptionList[name].push(callback);
return {
remove: () => {
this.subscriptionList[name] = this.subscriptionList[name].filter(
(cb) => cb !== callback
);
},
};
}
subscribeOnce(name, callback) {
const wrapper = (payload) => {
callback(payload);
this.subscriptionList[name].filter((cb) => cb !== wrapper);
};
this.subscribe(name, wrapper);
}
subscribeOnceAsync(name) {
return new Promise((resolve, reject) => {
const wrapper = (payload) => {
resolve(payload);
this.subscriptionList[name].filter((cb) => cb !== wrapper);
};
this.subscribe(name, wrapper);
});
}
publish(name, args) {
console.log('args...', args);
if(this.subscriptionList[name]){
this.subscriptionList[name].forEach((callback) => {
callback(args);
});
}
}
}
// Test cases
const events = new Events();
const newUserNewsSubscription = events.subscribe(
"new-user",
function (payload) {
console.log(`Sending Q1 News to: ${payload}`);
}
);
events.publish("new-user", "Jhon");
//output: "Sending Q1 News to: Jhon"
const newUserNewsSubscription2 = events.subscribe(
"new-user",
function (payload) {
console.log(`Sending Q2 News to: ${payload}`);
}
);
events.publish("new-user", "Doe");
//output: "Sending Q1 News to: Doe"
//output: "Sending Q2 News to: Doe"
newUserNewsSubscription.remove(); // Q1 news is removed
events.publish("new-user", "Foo");
//output: "Sending Q2 News to: Foo"
events.subscribeOnce("new-user", function (payload) {
console.log(`I am invoked once ${payload}`);
});
events.publish("new-user", "Foo Once");
//output: "Sending Q2 News to: Foo Once" - normal event
//output: "I am invoked once Foo Once" - once event
events.publish("new-user", "Foo Twice");
//output: "Sending Q2 News to: Foo Twice" - normal event
// once event should not invoke for second time
events.subscribeOnceAsync("new-user").then(function (payload) {
console.log(`I am invoked once ${payload}`);
});
events.publish("new-user", "Foo Once Async");