Event Emitter

Here is an example of writing your own Event Emitter module. However just use Nodes core event emitter

const Emitter = function Emitter() {
    this.events = {};
};
/* Javascript listeners are functions */
Emitter.prototype.on = function on(type, eventListener) {
    this.events[type] = this.events[type] || []; // If type has been passed through as an array add it or create a new array for it
    this.events[type].push(eventListener); // push my listener into the array
};
 
Emitter.prototype.emit = function emit(type) {
    if (this.events[type]) { // if i can find the property
        this.events[type].forEach( function(eventListener) { // for each function in the array, remember you can pass itself through the function
            eventListener(); // fir that function
        });
    }
};
 
module.exports = Emitter;
 
/*
This is all Emitter.prototype.on is doing...
{
    getSomeInfo : [ function(){}, function(){} ]
}
 
*/

It's best to put your event emitters inside an file so we geek the names all in once place

// config.js
 
module.exports = {
    events: {
        GREET: 'message',
        FILESAVED: 'filesaved',
        FILEOPENED: 'fileopened'
    }
}

Then to set and invoke your event emitters

const Emitter = require('events'); // node core emitter
const eventsConfig = require('./config').events;
 
// Our functions : Note you can have multiple actions (ie a chain) under one Emitter label
function addUser() {
  console.log('Added a user');
};
 
function removeUser() {
  console.log('Removed a user');
};
 
function message() {
  console.log('Yo Yo Yo');
};
 
// Emitter
var Emt = new Emitter();
 
Emt.on('registerUser', addUser ); 
Emt.on('registerUser', removeUser ); 
 
Emt.emit('registerUser'); // Echo's "Added a user, Removed a User"
 
// use my event emitter using config, much safer and cleaner
Emt.on(eventsConfig.GREET, ()=> {
  console.log('Yo Yo Yo');
});
 
Emt.emit(eventsConfig.GREET);
Unless otherwise stated, the content of this page is licensed under Creative Commons Attribution-ShareAlike 3.0 License