-
Notifications
You must be signed in to change notification settings - Fork 0
/
EventBus.js
35 lines (32 loc) · 1 KB
/
EventBus.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
var EventBus = (function() {
let obj = null
return function() {
if (obj === null && this instanceof EventBus) {
this.events = {}
this.on = function(event, fn) {
(this.events[event] || (this.events[event] = [])).push(fn)
}
this.emit = function(event, data) {
const cbs = this.events[event] || []
cbs.map(function(cb) {
cb(data)
})
}
this.off = function(event, fn) {
if (!fn) {
delete this.events[event]
} else {
const cbs = this.events[event] || []
for (let i=0, len=cbs.length; i<len; i++) {
if (fn === cbs[i]) {
cbs.splice(i, 1)
break
}
}
}
}
obj = this
}
return obj
}
}())