-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.js
48 lines (46 loc) · 1.01 KB
/
index.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
'use strict'
class PubSub {
constructor() {
this.topics = {}
this.subUid = -1
}
on(topic, func) {
if (!this.topics.hasOwnProperty(topic))
this.topics[topic] = []
var token = (++this.subUid).toString()
this.topics[topic].push({
token: token,
func: func
})
return token
}
trigger(topic, args) {
var subscribers = this.topics[topic]
if (!subscribers)
return false
var len = subscribers.length || 0
var i = 0
for(; i<len; i++)
subscribers[i] && typeof subscribers[i].func == 'function' && subscribers[i].func(args)
return true
}
off(token) {
for (var m in this.topics) {
if (this.topics[m]) {
for (var i = 0, j = this.topics[m].length; i < j; i++) {
if (this.topics[m][i].token === token) {
this.topics[m].splice(i, 1)
return token
}
}
}
}
}
clear() {
this.topics = {}
}
get allTopics() {
return this.topics
}
}
module.exports = new PubSub()