Skip to content

Instantly share code, notes, and snippets.

@brentertz
Created October 20, 2012 16:30
Show Gist options
  • Save brentertz/3923852 to your computer and use it in GitHub Desktop.
Save brentertz/3923852 to your computer and use it in GitHub Desktop.
Node.js: Extend a class to be an EventEmitter
var util = require('util'),
EventEmitter = require('events').EventEmitter;
var Server = function() {
var self = this;
this.on('custom_event', function() {
self.logSomething('custom_event');
});
this.logSomething('init');
};
util.inherits(Server, EventEmitter);
Server.prototype.doSomething = function() {
this.emit('custom_event');
};
Server.prototype.logSomething = function(something) {
console.log(something);
}
var s = new Server();
s.doSomething();
@elimence
Copy link

elimence commented Mar 5, 2015

you might want to add the following to the constructor

EventEmitter.call(this);

So that the object is initialized by EventEmitter's contructor

@4ley
Copy link

4ley commented Dec 12, 2015

@elimence, I guess you mean: so that the object fires the EventEmitter's contructor. Server inherits from EventEmitter.

@rebrec
Copy link

rebrec commented Feb 26, 2017

There is no class (es6) in this example.

@stephanelpaul
Copy link

There is no class (es6) in this example.
the example is from 9 years ago :P

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment