Last active
March 4, 2017 15:34
-
-
Save tamg/ad27dc38d18202a022334d6eefb0c4ee to your computer and use it in GitHub Desktop.
This file contains 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
//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