Skip to content

Instantly share code, notes, and snippets.

@saiumesh535
Created November 13, 2017 07:50
Show Gist options
  • Select an option

  • Save saiumesh535/df0cf5f8dc615afbef2948d75c1a0a24 to your computer and use it in GitHub Desktop.

Select an option

Save saiumesh535/df0cf5f8dc615afbef2948d75c1a0a24 to your computer and use it in GitHub Desktop.
Writing custom emitter's in nodejs
// let's code some emitters
function Emitter(){
this.events = {};
}
const emtr = new Emitter();
// on function to push events in array
Emitter.prototype.on = function(type,listener){
this.events[type] = this.events[type] || [];
this.events[type].push(listener);
}
// when you want to emit
Emitter.prototype.emit = function(type){
if(this.events[type]){
this.events[type].forEach(listener => {
listener();
});
}
}
// adding events to array
emtr.on("Namastey",()=>{
console.log("That's Hi in Hindi");
})
// emitting the events
emtr.emit("Namastey"); // this will print console
emtr.emit("Sss"); // and this won't
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment