antoniojps
4/9/2017 - 2:43 PM

Node JS Emitter

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