-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
72 lines (48 loc) · 1.34 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
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
var EventEmitter = require('events').EventEmitter;
var inherits = require('util').inherits;
function EventManager() {
EventEmitter.call(this);
}
inherits(EventManager, EventEmitter);
function parsePath(path) {
if (typeof path === 'string') {
if (path.length === 0) {
throw new Error('An empty path is not a valid event path');
}
return path.split('.');
}
if (Array.isArray(path)) {
if (path.length === 0) {
throw new Error('An empty path is not a valid event path');
}
// make a copy, because we'll be mutating it
return path.slice();
}
throw new TypeError('An event path must be a non-empty array or a string');
}
function createPathFamily(path) {
// longest paths first
var family = [];
path = parsePath(path);
while (path.length > 0) {
family.push(path.join('.'));
path.pop();
}
return family;
}
EventManager.prototype.emitEvent = function (fullPath, params) {
// accepts only a single params object (which may be of any type)
var paths = createPathFamily(fullPath);
for (var i = 0; i < paths.length; i += 1) {
this.emit(paths[i], fullPath, params);
}
};
EventManager.prototype.emitEvents = function (events) {
for (var i = 0; i < events.length; i += 1) {
var evt = events[i];
if (evt) {
this.emitEvent(evt[0], evt[1]); // magic array positions: path, params
}
}
};
module.exports = EventManager;