Skip to content

Instantly share code, notes, and snippets.

@senthil1216
Last active March 18, 2022 10:04
Show Gist options
  • Select an option

  • Save senthil1216/00aceea77a7eb8929d83e694d5d08f73 to your computer and use it in GitHub Desktop.

Select an option

Save senthil1216/00aceea77a7eb8929d83e694d5d08f73 to your computer and use it in GitHub Desktop.
Pub Sub in javascript
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();
@farabitarhan

Copy link
Copy Markdown

Elegant implementation. You should implement removeListeners and another version for Typescript as well.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment