-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathpubsub.js
80 lines (65 loc) · 1.56 KB
/
pubsub.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
69
70
71
72
73
74
75
76
77
78
79
80
class Pubsub {
constructor() {
this.subUid = 0
this.topics = {}
}
// 发送
publish(topic, args) {
if (!this.topics[topic]) {
return false
}
let subscribe = this.topics[topic]
let len = subscribe ? subscribe.length : 0
while (len--) {
subscribe[len].func(topic, args)
}
}
// 订阅
subscribe(topic, func) {
if (!this.topics[topic]) {
this.topics[topic] = []
}
this.subUid++
this.topics[topic].push({
token: this.subUid,
func: func
})
}
// 取消订阅
unsubscribe(token) {
for (let item in this.topics) {
if (this.topics[item]) {
this.topics[item].forEach((sub, index) => {
if (sub.token === token) {
this.topics[item].splice(index, 1)
}
});
}
}
}
}
const mail = new Pubsub()
let mailCount = 0
const A = mail.subscribe('inbox/newMessage', function (topic, args) {
console.log(topic)
console.info(args)
mailCount++
})
const B = mail.subscribe('inbox/newMessage', function (topic, args) {
console.log(topic)
console.info(args)
mailCount++
})
// mail.unsubscribe(1) mailCount = 1
mail.publish('inbox/newMessage', [{ sender: '[email protected]', content: "hi,...." }])
console.log(mailCount) // mailCount = 2
const message = new Pubsub()
const A = message.subscribe('weather', function (topic, args) {
console.log(topic)
console.info(args)
})
const B = message.subscribe('weather', function (topic, args) {
console.log(topic)
console.info(args)
})
message.publish('weather', [{ info: '阵雨' }])