Last active
October 30, 2016 16:01
-
-
Save mnyamor/4547def17f4e5cefa330f6668d36bfc7 to your computer and use it in GitHub Desktop.
Handling Events With EventEmitter
This file contains hidden or 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
| /*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