Skip to content

Instantly share code, notes, and snippets.

@satyam4p
Created January 14, 2024 05:48
Show Gist options
  • Save satyam4p/405de3ebacb78a622b9ffa402c5a8e4e to your computer and use it in GitHub Desktop.
Save satyam4p/405de3ebacb78a622b9ffa402c5a8e4e to your computer and use it in GitHub Desktop.
Revealing constructor pattern example through event emitter
const EEStoEventMaps = new WeakMap();
export default class EventEmitter{
constructor(publisher){
const eventMap = Object.create(null);
EEStoEventMaps.set(this, eventMap);
publisher(makePublish(this));
}
on(eventName, handler){
const eventMap = EEStoEventMaps.get(this);
let handlers = eventMap[eventName];
if(!handlers){
handlers = eventMap[eventName] = [];
}
handlers.push(handler);
}
off(eventName, handler){
const eventMap = EEStoEventMaps.get(this);
let handlers = eventMap[eventName];
if(!handlers){
return;
}
const index = handlers.indexOf(handler);
if(index === -1){
return;
}
handlers.splice(index, 1);
}
}
function makePublish(eventEmitter){
const eventMap = EEStoEventMaps.get(eventEmitter);
return function(eventName, ...args){
const handlers = eventMap[eventName];
if(handlers){
handlers.forEach(handler =>handler(...args));
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment