Skip to content

Instantly share code, notes, and snippets.

@mrnejc
Created September 17, 2015 12:15
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 mrnejc/1b00649e7f125cdc029a to your computer and use it in GitHub Desktop.
Save mrnejc/1b00649e7f125cdc029a to your computer and use it in GitHub Desktop.
recipe to create event emitting class in nodejs
// 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