-
Notifications
You must be signed in to change notification settings - Fork 1
/
Pubsub.js
66 lines (56 loc) · 1.86 KB
/
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
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
class Observable {
constructor() {
this.subscribers = new Map(); // Map to hold subscribers and their callbacks
}
// Subscribe an observer with a callback
subscribe(callback) {
const id = Symbol(); // Unique ID for each subscription
this.subscribers.set(id, callback);
return {
unsubscribe: () => this.subscribers.delete(id),
};
}
// Notify all subscribers with data
notify(data) {
this.subscribers.forEach((callback) => callback(data));
}
}
class Observer {
constructor(name) {
this.name = name;
this.subscriptions = []; // Track all subscriptions
}
// Subscribe to an observable and keep track of the subscription
addSubscription(observable, callback) {
const subscription = observable.subscribe(callback);
this.subscriptions.push(subscription);
return subscription;
}
// Unsubscribe from all subscriptions
unsubscribeAll() {
this.subscriptions.forEach((subscription) => subscription.unsubscribe());
this.subscriptions = []; // Clear the list
}
}
// Create an observable
const observable = new Observable();
// Create observers
const observer1 = new Observer("Observer 1");
const observer2 = new Observer("Observer 2");
// Observer 1 subscribes to the observable with multiple callbacks
const subscription1 = observer1.addSubscription(observable, (data) =>
console.log(`${observer1.name} received data: ${data}`)
);
const subscription2 = observer1.addSubscription(observable, (data) =>
console.log(`${observer1.name} received additional data: ${data}`)
);
// Observer 2 subscribes to the observable
const subscription3 = observer2.addSubscription(observable, (data) =>
console.log(`${observer2.name} received data: ${data}`)
);
// Emit events
observable.notify("Event 1");
// Unsubscribe Observer 1 from one callback
subscription1.unsubscribe();
// Emit another event
observable.notify("Event 2");