-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathpubsubscribe.js
66 lines (56 loc) · 1.25 KB
/
pubsubscribe.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
var pubsub = {}
var topics = {}, subUid = -1
pubsub.publish = function (topic, args) {
if (!topics[topic]) {
return false
}
console.log(1)
var subscribers = topics[topic], len = subscribers ? subscribers.length : 0
while (len--) {
subscribers[len].func(topic, args)
}
}
pubsub.subscribe = function (topic, func) {
if (!topics[topic]) {
topics[topic] = []
}
subUid++
topics[topic].push({
token: subUid,
func: func
})
}
pubsub.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 this
}
/*---mail example---*/
var mailCounter = 0
var subscribe1 = pubsub.subscribe("inbox/newMessage", function (topic, data) {
console.log("topic", topic)
console.log(data)
mailCounter++
})
var subscribe2 = pubsub.subscribe("test", function (topic, data) {
console.log("topic", topic)
console.log(data)
mailCounter++
})
pubsub.publish('inbox/newMessage', [{
sender: '[email protected]',
body: 'hey...'
}])
pubsub.publish('test', [{
sender: '[email protected]',
body: 'hey...'
}])
console.log(mailCounter)