-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathPubSub.js
More file actions
60 lines (51 loc) · 1.51 KB
/
PubSub.js
File metadata and controls
60 lines (51 loc) · 1.51 KB
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
class PubSub {
constructor() {
this.channels = {};
}
/**
* subscribe to any events (channels);
* @param {string} channel
* @param {Function} cb
* @returns {string} returns unique id per channel for the subscriber
*/
subscriber(channel, cb) {
const id = (new Date().getTime()).toString(36);
this.channels[channel] = this.channels[channel] || {};
this.channels[channel][id] = cb;
// return token for unsubscribing
return id;
}
/**
* unsubscribe from any events (channels)
* @param {string} channel
* @param {string} id
*/
unsubscribe(channel, id) {
if (this.channels[channel][id]) {
delete this.channels[channel][id];
console.log(`Unsubscribing ${channel}`);
}
}
/**
* call every subscribed listener with data on publishing the event (channel)
* @param {string} channel
* @param {any} data
*/
publish(channel, data) {
if (this.channels[channel]) {
const [key] = Object.keys(this.channels[channel]);
if(this.channels[channel][key]) {
this.channels[channel][key](data);
} else {
console.warn(`Unable to publish ${channel}`);
}
}
}
}
const mouth = new PubSub();
const shoutToken = mouth.subscriber('shout', (e) => console.log('shouting ', e))
const whisperToken = mouth.subscriber('whisper', (e) => console.log('whispering', e))
mouth.publish('shout', 'pubSub!!!');
mouth.publish('whisper', 'pubSub...');
mouth.unsubscribe('whisper', whisperToken);
mouth.publish('whisper', 'whuutt');