forked from temmihoo/plushie-badname
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathPubSub.js
More file actions
55 lines (45 loc) · 1.25 KB
/
PubSub.js
File metadata and controls
55 lines (45 loc) · 1.25 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
module.exports.pubsub = function(){
"use strict";
var ps = {},
topics = {},
subId = -1;
ps.publish = function(topic, args){
if (!topics[topic]){
console.log("No subscriber found\n");
return false;
}
var subscribers = topics[topic],
len = subscribers ? subscribers.length : 0;
while ((len --) > 0){
subscribers[len].func(args);
}
return this;
};
ps.subscribe = function(topic, func){
if (!topics[topic]){
topics[topic] = [];
}
var token = (++subId).toString();
topics[topic].push({
token: token,
func: func
});
return token;
};
ps.unsubscribe = function(token){
for (var topic in topics){
if (topics[topic]){
for (var i = 0; i < topics[topic].length; i++){
if (topics[topic][i].token === 'token'){
topics[topic].splice(i, 1);
return token;
}
}
}
}
};
ps.getTopics = function(){
return topics;
};
return ps;
};