-
Notifications
You must be signed in to change notification settings - Fork 0
/
pubsub.js
67 lines (44 loc) · 855 Bytes
/
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
// ** Very tiny and simple ES6 Publish/Subscribe **
class PubSub {
constructor() {
this.events = {};
}
publish(name, obj) {
let e = this.events[name];
if(!e) {
return;
}
let arg = arguments;
if(this.async) {
}
e.forEach(fn => fn.apply(this, [obj]));
}
subscribe(name, func) {
let _this = this;
if(!this.events[name]) {
this.events[name] = [];
}
const index = this.events[name].push(func) -1;
return {
_index: index,
name: name,
remove: () => _this.remove(name, index)
}
}
remove(name, index) {
let e = this.events[name];
if(e && typeof index === 'undefined') {
delete this.events[name];
return true;
}
if(e && e[index]) {
delete e[index];
return true;
}
return false;
}
getEvents() {
return this.events;
}
}
export default PubSub