@nguyentc21/event-listener
Version:
A simple Event Listener for JavaScript projects
76 lines (75 loc) • 2.34 kB
JavaScript
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.default = void 0;
const isValidId = id => {
if (['string', 'number', 'symbol'].includes(typeof id)) return true;
return false;
};
class EventListener {
constructor(name, isDebug) {
this.name = name;
this.isDebug = isDebug;
this.LISTENER_DATA = {};
}
addListener(id, callback, description) {
if (!isValidId(id) || callback && typeof callback !== 'function') return;
this.LISTENER_DATA[id] = {
id,
callback,
description
};
if (!!this.isDebug) {
console.log(`${this.name} - Add listener (∑${Object.keys(this.LISTENER_DATA).length}): `, id);
}
return id;
}
removeListener(id) {
if (!id || !isValidId(id) || !(id in this.LISTENER_DATA)) return false;
delete this.LISTENER_DATA[id];
if (!!this.isDebug) {
console.log(`${this.name} - Remove listener (∑${Object.keys(this.LISTENER_DATA).length}): `, id);
}
return true;
}
removeAllListeners() {
this.LISTENER_DATA = {};
if (!!this.isDebug) {
console.log(`${this.name} - Remove ALL listener (∑${Object.keys(this.LISTENER_DATA).length})`);
}
}
emitListener(id, data) {
var _this$LISTENER_DATA$i, _this$LISTENER_DATA$i2;
if (!(id in this.LISTENER_DATA)) return;
if (!!this.isDebug) {
console.log(`${this.name} - Emit listener (∑${Object.keys(this.LISTENER_DATA).length}): `, id);
}
return (_this$LISTENER_DATA$i = this.LISTENER_DATA[id]) === null || _this$LISTENER_DATA$i === void 0 || (_this$LISTENER_DATA$i2 = _this$LISTENER_DATA$i.callback) === null || _this$LISTENER_DATA$i2 === void 0 ? void 0 : _this$LISTENER_DATA$i2.call(_this$LISTENER_DATA$i, data);
}
getListenerList() {
return Object.values(this.LISTENER_DATA).map(el => {
if (!el) return undefined;
return {
id: el.id,
description: el.description
};
});
}
on = this.addListener;
emit = this.emitListener;
rm = this.removeListener;
rmAll = this.removeAllListeners;
emitPromise(id, data) {
return new Promise((resolve, reject) => {
this.emitListener(id, {
...data,
cb: resolve,
rj: reject
});
});
}
}
var _default = EventListener;
exports.default = _default;
//# sourceMappingURL=index.js.map