Last active
March 18, 2022 10:04
-
-
Save senthil1216/00aceea77a7eb8929d83e694d5d08f73 to your computer and use it in GitHub Desktop.
Pub Sub in javascript
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
class EventEmitters { | |
constructor(){ | |
this.listeners = new Map(); | |
this.addListeners = this.addListeners.bind(this); | |
this.emit = this.emit.bind(this); | |
} | |
addListeners(label, callBack){ | |
let callBacks = []; | |
if(this.listeners.has(label)){ | |
callBacks = this.listeners.get(label); | |
} | |
callBacks.push(callBack); | |
this.listeners.set(label, callBacks); | |
console.log(label, this.listeners); | |
} | |
emit(label){ | |
console.log(label, this.listeners); | |
if(!this.listeners.has(label)) { | |
console.error('no listeners found'); | |
} else { | |
const callBacks = this.listeners.get(label); | |
callBacks.forEach((cb) => { | |
cb(); | |
}); | |
} | |
} | |
} | |
class ModuleA { | |
constructor(evt) { | |
this.evt = evt | |
} | |
emitData(){ | |
this.evt.emit('done'); | |
} | |
} | |
class ModuleB { | |
constructor(evt) { | |
this.evt = evt | |
} | |
add(){ | |
this.evt.addListeners('done', () => { | |
console.log('callBack executed'); | |
}) | |
} | |
} | |
// .. testing methods | |
const eventObj = new EventEmitters(); | |
const moduleAObj = new ModuleA(eventObj); | |
const moduleBObj = new ModuleB(eventObj); | |
moduleBObj.add(); | |
moduleAObj.emitData(); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Elegant implementation. You should implement removeListeners and another version for Typescript as well.