Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Node.js - Best method for emitting events from modules

I've been playing around with the EventEmitter, but I'm confused about how exactly I should implement it from a module. I've seen a few different ways, and they all seem to work. Here are a few I've seen:

From here:

var Twitter = function() {...};

Twitter.prototype = new events.EventEmitter;

But then in "Mastering Node" they do it this way:

function Dog(name) {
  this.name = name;
  EventEmitter.call(this);
}

Dog.prototype.__proto__ = EventEmitter.prototype;

(why would you need to .call it?)

And then in my own code I tried yet another way:

function Class() {}

Class.prototype = EventEmitter.prototype;

They're all just inheriting from EventEmitter in their own way, so wouldn't the simplest solution be the best?

like image 251
Kevin McTigue Avatar asked Jul 31 '11 21:07

Kevin McTigue


1 Answers

Node has a library function, util.inherits, that is slightly more straightforward than the accepted answer. Code below is modified from the v0.8.12 docs.

var util = require("util");
var events = require("events");

function MyStream() {
  events.EventEmitter.call(this);
}

util.inherits(MyStream, events.EventEmitter);
like image 149
bmavity Avatar answered Sep 17 '22 02:09

bmavity