-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathpubsub.js
More file actions
76 lines (52 loc) · 1.63 KB
/
pubsub.js
File metadata and controls
76 lines (52 loc) · 1.63 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
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
"use strict";
var _ = require('lodash');
var PubSub = function (config) {
config = config || {};
this.evCache = {};
this.cbCache = {};
this.debug = config.debug || false;
};
PubSub.prototype.publish = function(eventName, data) {
if (this.debug) { console.log('PUBLISH', eventName, data); }
this.evCache[eventName] = this.evCache[eventName] || {
cache: undefined,
uids: []
};
_.forEach(this.evCache[eventName].uids, function (uid) {
this.cbCache[uid].fn(data, this.evCache[eventName].cache)
}.bind(this));
this.evCache[eventName].cache = data;
};
PubSub.prototype.subscribe = function(eventName, callback) {
if (this.debug) { console.log('SUBSCRIBE', eventName, callback); }
if (!(eventName && callback)) {
throw new Error();
}
var uid = _.uniqueId(eventName);
this.evCache[eventName] = this.evCache[eventName] || {
cache: undefined,
uids: []
};
this.evCache[eventName].uids.push(uid);
this.cbCache[uid] = {fn: callback, eventName: eventName};
return uid;
};
PubSub.prototype.unsubscribe = function(uid) {
if (this.debug) { console.log('UNSUBSCRIBE', uid); }
if (!uid) {
throw new Error();
}
var eventName = this.cbCache[uid] && this.cbCache[uid].eventName;
this.evCache[eventName].uids = _.reject(this.evCache[eventName].uids, function (_uid) {
return _uid === uid;
});
delete this.cbCache[uid];
};
PubSub.prototype.getCache = function(eventName) {
if (this.debug) { console.log('GETCACHE', eventName); }
if (!eventName) {
throw new Error();
}
return this.evCache[eventName] && this.evCache[eventName].cache;
};
module.exports = new PubSub();