2019-02-27 17:17:51 +01:00
|
|
|
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);
|
|
|
|
}
|
2018-10-31 17:00:31 +01:00
|
|
|
|
2019-02-27 17:17:51 +01:00
|
|
|
removeListener(label, callback) {
|
|
|
|
var isFunction = function(obj) {
|
|
|
|
return typeof obj == 'function' || false;
|
|
|
|
};
|
2018-10-31 17:00:31 +01:00
|
|
|
|
2019-02-27 17:17:51 +01:00
|
|
|
var listeners = this.listeners.get(label),
|
|
|
|
index;
|
2018-10-31 17:00:31 +01:00
|
|
|
|
2019-02-27 17:17:51 +01:00
|
|
|
if (listeners && listeners.length) {
|
|
|
|
index = listeners.reduce((i, listener, index) => {
|
|
|
|
return isFunction(listener) && listener === callback ? (i = index) : i;
|
|
|
|
}, -1);
|
2018-10-31 17:00:31 +01:00
|
|
|
|
2019-02-27 17:17:51 +01:00
|
|
|
if (index > -1) {
|
|
|
|
listeners.splice(index, 1);
|
|
|
|
this.listeners.set(label, listeners);
|
|
|
|
return true;
|
|
|
|
}
|
|
|
|
}
|
|
|
|
return false;
|
|
|
|
}
|
2018-10-31 17:00:31 +01:00
|
|
|
|
2019-02-27 17:17:51 +01:00
|
|
|
emitEvent(label, ...args) {
|
|
|
|
var listeners = this.listeners.get(label);
|
|
|
|
if (listeners && listeners.length) {
|
|
|
|
listeners.forEach(listener => {
|
|
|
|
listener(...args);
|
|
|
|
});
|
|
|
|
return true;
|
|
|
|
}
|
|
|
|
return false;
|
|
|
|
}
|
|
|
|
//--------------------------
|
|
|
|
// event handlers
|
|
|
|
//--------------------------
|
2018-10-31 17:00:31 +01:00
|
|
|
}
|
2019-02-27 17:17:51 +01:00
|
|
|
export default EventEmitter;
|