This repository was archived by the owner on Dec 10, 2019. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathEventEmitter.js
More file actions
77 lines (65 loc) · 2.13 KB
/
Copy pathEventEmitter.js
File metadata and controls
77 lines (65 loc) · 2.13 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
/**
* EventEmitter - a basic JavaScript event handler
*/
(function(root, factory) {
if (typeof define === "function" && define.amd) {
define(["EventEmitter"], factory);
} else if (typeof module === "object" && module.exports) {
module.exports = factory();
} else {
root.EventEmitter = factory();
}
}(this, function(undefined) {
/**
* @constructor
*/
var EventEmitter = function() {
/**
* holds all events with their respective event handlers
*
* @type {Object}
*/
this.oEvents = {};
};
/**
* bind callbacks you want to invoke on emit of a specific event name
*
* @param {String} sEventName - event name
* @param {Function} eventHandler - event handler function
*
* @returns {EventEmitter}
*/
EventEmitter.prototype.on = function(sEventName, eventHandler) {
if (typeof sEventName !== 'string' || sEventName.trim() === '') {
throw new TypeError('sEventName argument is not of a valid type or empty');
}
if (typeof eventHandler !== 'function') {
throw new TypeError('eventHandler argument is not a function');
}
if (!this.oEvents[sEventName]) {
this.oEvents[sEventName] = [];
}
this.oEvents[sEventName].push(eventHandler);
return this;
};
/**
* emit event callbacks by event name
*
* @param {String} sEventName the event name you want to emit
* @param {Generic} gData any kind of additional data you want to transfer to the eventHandler function
*
* @returns {EventEmitter}
*/
EventEmitter.prototype.emit = function(sEventName, gData) {
if (typeof sEventName !== 'string' || sEventName.trim() === '') {
throw new TypeError('sEventName argument is not of a valid type or empty');
}
if (this.oEvents[sEventName]) {
this.oEvents[sEventName].forEach(function(eventHandler) {
eventHandler(gData);
});
}
return this;
};
return EventEmitter;
}));