Skip to content

Instantly share code, notes, and snippets.

@antoniojps
Created April 9, 2017 14:43
Show Gist options
  • Save antoniojps/51fda14143a89c107ce5547fdad51f2c to your computer and use it in GitHub Desktop.
Save antoniojps/51fda14143a89c107ce5547fdad51f2c to your computer and use it in GitHub Desktop.
Node JS Emitter
// Emitter.js
// function constructor for event
function Emitter() {
this.events = {};
}
// prototype method to add listener (array of functions)
Emitter.prototype.on = function (type, listener) {
this.events[type] = this.events[type] || [];
this.events[type].push(listener);
};
// prototype method to emit event (call listeners/functions of the array)
Emitter.prototype.emit = function (type) {
if (this.events[type]) { // If exists
this.events[type].forEach(function (listener) { // Invoke listeners ( functions of the array of the type of event )
listener();
})
}
};
module.exports = Emitter;
// config.js
module.exports = {
events : {
GREET: 'greet'
}
};
// app.js
var Emitter = require ('events');
var emtr = new Emitter();
var eventConfig = require('./config').events;
emtr.on(eventConfig.GREET,function(){
console.log('Hello World');
});
emtr.emit(eventConfig.GREET); // Event triggered
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment