Created
September 17, 2015 12:15
-
-
Save mrnejc/1b00649e7f125cdc029a to your computer and use it in GitHub Desktop.
recipe to create event emitting class in nodejs
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
// created from example at http://thejackalofjavascript.com/node-js-design-patterns/ | |
// and using nodejs.org docs | |
var EventEmitter = require('events').EventEmitter; | |
var util = require('util'); | |
function Batter(name) { | |
this.name = name; | |
// initialize properties from EventEmitter on this instance | |
EventEmitter.call(this); | |
this.swing = function() { | |
console.log('function swing() called, will emit strike event'); | |
this.emit('swing'); | |
} | |
} | |
// make Batter inherit functions from EventEmitter (on, emit, ...) | |
// this is direct prototype asignment way - tested and works | |
//Batter.prototype = EventEmitter.prototype; | |
// but this is the documented way https://nodejs.org/api/events.html | |
util.inherits(Batter, events.EventEmitter); | |
// create new istance of batter | |
var b = new Batter('Babe Ruth'); | |
b.on('swing', function() { console.log('It is a Strrikkkeee!!!!'); }); | |
// now call function | |
// that emits 'swing' | |
// and this calls on('swing') callback | |
b.swing(); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment