Skip to content

Instantly share code, notes, and snippets.

Last active Mar 4, 2017
What would you like to do?
//example by Anthony Alicea
//Inheriting from the Event Emitter using util.inherits
var EventEmitter = require('events');
var util = require('util');
function Greetr() {
//everytime we call new Greetr(), methods of EventEmitter are added to the new 'this'
//same as calling super() in ES6;
//and then add our own method in addition to ones inherited from EventEmitter
this.greeting = 'Hello world!';
//Greetr(constructor) inherits methods and properties of EventEmitter(superconstructor)
util.inherits(Greetr, EventEmitter);
//add our own method greet on the Greetr constructor
//we can now also use emit because Greetr is inheriting from EventEmitter
//we can also pass a 'data' along with the emitted event
Greetr.prototype.greet = function(data) {
console.log(this.greeting + ': ' + data);
this.emit('greet', data);
//create a new object greeter1
var greeter1 = new Greetr();
greeter1.on('greet', function(data) {
console.log('Someone greeted!: ' + data);
//Hello World!: Jane
//Someone greeted!: Jane
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment