Created
January 14, 2024 05:48
-
-
Save satyam4p/405de3ebacb78a622b9ffa402c5a8e4e to your computer and use it in GitHub Desktop.
Revealing constructor pattern example through event emitter
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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