Skip to content

Instantly share code, notes, and snippets.

@mnyamor
Created October 30, 2016 16:31
Show Gist options
  • Save mnyamor/53eb3f387e021a8cd286864662268e4f to your computer and use it in GitHub Desktop.
Save mnyamor/53eb3f387e021a8cd286864662268e4f to your computer and use it in GitHub Desktop.
Exporting Custom Modules
var EventEmitter = require('events').EventEmitter;
var util = require('util');
var Person = function(name) {
this.name = name;
};
util.inherits(Person, EventEmitter);
/* module.exports = Person; -> object returned by the require export.
we could export this, move it to a separate file then require it as a separate module..
e.g. var Person = require("./lib/Person");
*/
// We can also use this person object to create more people...
var ben = new Person("Ben Franklin");
var Mary = new Person("Mary Nyamor");
// We can also wire up listeners on these other instances
Mary.on('speak', function(said) {
// we'll log what Mary said..
console.log(`${this.name} -> ${said}`);
});
/* Another person listener..
now we have used our person object to create another instances of Person.
That means that we can use this person object over and over again in all of
our files because of the common JS module pattern (in the case of module.exports);
*/
ben.on('speak', function(said) {
console.log(`${this.name}: ${said}`);
});
ben.emit('speak', "You may delay, but time will not.");
Mary.emit('speak', "It is far better to be alone, than to be in bad company.");
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment