I've written the following custom event system module and I'm planning to use it in production in the future. Before I do that, I'd like to ask for general suggestions on how to improve it. Thanks a lot.
const event = (function() {
let registry = {};
function on(event, callback) {
if(!registry[event]) registry[event] = [];
registry[event].push(callback);
}
function once(event, callback) {
if(!registry[event]) registry[event] = [];
registry[event].push(function(message) {
callback(message);
off(event, callback);
});
}
function off(event, callback) {
if(registry[event]) {
registry[event].splice(registry[event].indexOf(callback), 1);
if(!registry[event].length) delete registry[event];
}
}
function emit(event, message) {
if(registry[event]) {
registry[event].forEach(callback => {
callback(message);
});
}
}
function getListeners(event) {
return registry[event] ? registry[event] : null;
}
return {
on: on,
once: once,
off: off,
emit: emit,
getListeners: getListeners
}
})();
export { event };
Usage:
Add event listener:
event.on('someEvent', someEventhandler);
Remove event listener:
event.off('someEvent', someEventhandler);
Add event listener and remove it after first use:
event.once('someEvent', someEventhandler);
Fire the event:
event.emit('someEvent');
Get all eventhandlers for an event:
event.getListeners('someEvent');