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?
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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With