Skip to content

Instantly share code, notes, and snippets.

@mnyamor
Last active October 30, 2016 16:01
Show Gist options
  • Select an option

  • Save mnyamor/4547def17f4e5cefa330f6668d36bfc7 to your computer and use it in GitHub Desktop.

Select an option

Save mnyamor/4547def17f4e5cefa330f6668d36bfc7 to your computer and use it in GitHub Desktop.
Handling Events With EventEmitter
/*The Event Emitter is Node.js's implementation of the pub/sub design pattern.
It allows us to create listeners for an emit custom Events.
In fact, every time we've used that on function to listen for a new Event,
we've already been using an implementation of the EventEmitter.
*/
// create a variable for events and require the events module
var events = require('events');
// create a new instance of a variable called emitter by using the new keyword with the event module, .Event Emitter
// The EventEmitter is a constructor and we create a new instance of the EventEmitter.
// So, every time we use on, we can wire up a custom event.
var emitter = new events.EventEmitter();
/* The second argument that the on function takes is a callback function that will be invoked when the custom event is raised.
In this case, our custom event is going to pass a message and a status to this function as arguments.
So, when our custom event occurs, this callback function will be invoked asynchronously.
*/
emitter.on('customEvent', function(message, status) {
console.log(`${status} : ${message} `);
});
// created a new instance of the EventEmitter object & we wired up a listener to listen for custom events.
emitter.emit('customEvent', 'Hello World', 200);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment