Repository navigation
Expand file tree
/
Copy pathevents.js
More file actions
78 lines (71 loc) · 1.74 KB
/
Copy pathevents.js
File metadata and controls
78 lines (71 loc) · 1.74 KB
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
/**
* @module eventDispatcher
*
* Has two important methods:
* - {Function} on - appends subscriber to the event. If event doesn't exist - creates new one
* - {Function} emit - fires all subscribers with data
* - {Function off - unsubsribes callback
*
* @version 1.0.0
*
* @typedef {Events} Events
* @property {Object} subscribers - all subscribers grouped by event name
*/
export default class Events extends Module {
/**
* @constructor
*/
constructor({config}) {
super({config});
this.subscribers = {};
}
/**
* Subscribe any event on callback
*
* @param {String} eventName - event name
* @param {Function} callback - subscriber
*/
on(eventName, callback) {
if (!(eventName in this.subscribers)) {
this.subscribers[eventName] = [];
}
// group by events
this.subscribers[eventName].push(callback);
}
/**
* Emit callbacks with passed data
*
* @param {String} eventName - event name
* @param {Object} data - subscribers get this data when they were fired
*/
emit(eventName, data) {
if (!this.subscribers[eventName]) {
return;
}
this.subscribers[eventName].reduce(function (previousData, currentHandler) {
let newData = currentHandler(previousData);
return newData ? newData : previousData;
}, data);
}
/**
* Unsubsribe callback from event
*
* @param eventName
* @param callback
*/
off(eventName, callback) {
for(let i = 0; i < this.subscribers[eventName].length; i++) {
if (this.subscribers[eventName][i] === callback) {
delete this.subscribers[eventName][i];
break;
}
}
}
/**
* Destroyer
* clears subsribers list
*/
destroy() {
this.subscribers = null;
}
}