forked from addyosmani/pubsubz
-
Notifications
You must be signed in to change notification settings - Fork 0
/
pubsubz.js
68 lines (52 loc) · 1.4 KB
/
pubsubz.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
/*!
* Pub/Sub implementation
* http://addyosmani.com/
* Licensed under the GPL
* http://jsfiddle.net/LxPrq/
*/
;(function ( window, doc, undef ) {
var topics = {},
subUid = -1,
pubsubz ={};
pubsubz.publish = function ( topic, args ) {
if (!topics[topic]) {
return false;
}
setTimeout(function () {
var subscribers = topics[topic],
len = subscribers ? subscribers.length : 0;
while (len--) {
subscribers[len].func(topic, args);
}
}, 0);
return true;
};
pubsubz.subscribe = function ( topic, func ) {
if (!topics[topic]) {
topics[topic] = [];
}
var token = (++subUid).toString();
topics[topic].push({
token: token,
func: func
});
return token;
};
pubsubz.unsubscribe = function ( token ) {
for (var m in topics) {
if (topics[m]) {
for (var i = 0, j = topics[m].length; i < j; i++) {
if (topics[m][i].token === token) {
topics[m].splice(i, 1);
return token;
}
}
}
}
return false;
};
getPubSubz = function(){
return pubsubz;
};
window.pubsubz = getPubSubz();
}( this, this.document ));