Created
April 9, 2017 14:43
-
-
Save antoniojps/51fda14143a89c107ce5547fdad51f2c to your computer and use it in GitHub Desktop.
Node JS Emitter
This file contains 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
// 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