Skip to content

Instantly share code, notes, and snippets.

@tamg
Last active March 4, 2017 15:34
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save tamg/ad27dc38d18202a022334d6eefb0c4ee to your computer and use it in GitHub Desktop.
Save tamg/ad27dc38d18202a022334d6eefb0c4ee to your computer and use it in GitHub Desktop.
//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
EventEmitter.call(this);
//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);
});
greeter1.greet('Jane');
//Hello World!: Jane
//Someone greeted!: Jane
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment