You cannot select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
53 lines
1.2 KiB
JavaScript
53 lines
1.2 KiB
JavaScript
6 years ago
|
class EventEmitter {
|
||
|
//--------------------------
|
||
|
// constructor
|
||
|
//--------------------------
|
||
|
constructor() {
|
||
|
this.listeners = new Map();
|
||
|
}
|
||
|
//--------------------------
|
||
|
// methods
|
||
|
//--------------------------
|
||
|
addListener(label, callback) {
|
||
|
this.listeners.has(label) || this.listeners.set(label, []);
|
||
|
this.listeners.get(label).push(callback);
|
||
|
}
|
||
6 years ago
|
|
||
6 years ago
|
removeListener(label, callback) {
|
||
|
var isFunction = function(obj) {
|
||
|
return typeof obj == 'function' || false;
|
||
|
};
|
||
6 years ago
|
|
||
6 years ago
|
var listeners = this.listeners.get(label),
|
||
|
index;
|
||
6 years ago
|
|
||
6 years ago
|
if (listeners && listeners.length) {
|
||
|
index = listeners.reduce((i, listener, index) => {
|
||
|
return isFunction(listener) && listener === callback ? (i = index) : i;
|
||
|
}, -1);
|
||
6 years ago
|
|
||
6 years ago
|
if (index > -1) {
|
||
|
listeners.splice(index, 1);
|
||
|
this.listeners.set(label, listeners);
|
||
|
return true;
|
||
|
}
|
||
|
}
|
||
|
return false;
|
||
|
}
|
||
6 years ago
|
|
||
6 years ago
|
emitEvent(label, ...args) {
|
||
|
var listeners = this.listeners.get(label);
|
||
|
if (listeners && listeners.length) {
|
||
|
listeners.forEach(listener => {
|
||
|
listener(...args);
|
||
|
});
|
||
|
return true;
|
||
|
}
|
||
|
return false;
|
||
|
}
|
||
|
//--------------------------
|
||
|
// event handlers
|
||
|
//--------------------------
|
||
6 years ago
|
}
|
||
6 years ago
|
export default EventEmitter;
|