Skip to content

Instantly share code, notes, and snippets.

@mnyamor
Created October 30, 2016 16:18
Show Gist options
  • Save mnyamor/bace1346aebb049ffb5064d17a79de5f to your computer and use it in GitHub Desktop.
Save mnyamor/bace1346aebb049ffb5064d17a79de5f to your computer and use it in GitHub Desktop.
Handling Events With EventEmitter 2
var EventEmitter = require('events').EventEmitter;
// We can use the utilities module to help us to have the Person object inherit the EventEmitter
var util = require('util');
/* -create a Person object
-create a constructor function here for this object
-in this constructor function, we're going to take in the Person's name
*/
var Person = function(name) {
// this Person's name will be set to the name value that is passed to this constructor function.
this.name = name;
};
/* So, this one line here has just added the EventEmiiter to the Person's prototype,
which means that the Person object inherits all of the functionality from the EventEmitter.
If I create a new instance of a Person, it will have an on and emit function.
*/
util.inherits(Person, EventEmitter);
/*****
EXAMPLE 1:
- create a new instance of a person called ben
- Ben can listen for custom events...
ben.on('speak', function(said) { console.log(`${this.name}`); });
var ben = new Person('Ben');
ben.emit('speak', 'You may delay but time wil not')
*/
module.exports = Person;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment