Skip to content

Instantly share code, notes, and snippets.

@Maxondria
Created May 14, 2019 19:22
Show Gist options
  • Save Maxondria/a4761c946901302f3b245de32fb03afd to your computer and use it in GitHub Desktop.
Save Maxondria/a4761c946901302f3b245de32fb03afd to your computer and use it in GitHub Desktop.
Custom Node Event Emitter
//emitter.js
const Emitter = function(){
this.events = {}
}
Emitter.prototype.on = function(type, callback){
this.events[type] = this.events[type] || [];
this.events[type].push(callback);
}
Emitter.prototype.emit = function(type, data){
if(this.events[type]){
this.events[type].forEach(callback => {
callback(data);
})
}
}
module.exports.Emitter = Emitter;
//index.js
const { Emitter } = require('./Emiiter');
const emitr = new Emitter();
emitr.on('customEvent', function(data){
console.log('Holla, data is: ',data);
});
for(let i = 0; i < 3; i++){
emitr.emit('customEvent', {
name: 'maxBigBudget',
valueI: i
});
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment