Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is events.EventEmitter.call(this) required when creating a custom EventEmitter?

There are a lot of example not using events.EventEmitter.call(this) in custom event emitter constructors, while other are using it (official documentation):

var events = require('events')
  , util   = require('util');

var MyEmitter = function () {
    events.EventEmitter.call(this);
};

util.inherits(MyEmitter, events.EventEmitter);

MyEmitter.prototype.write = function () {
    this.emit('tick');
};

With my basic understandings of JavaScript I don't know if I need it. Is the call necessary to to initialization stuff inside the EventEmitter?

like image 952
gremo Avatar asked May 21 '13 15:05

gremo


People also ask

How do you call an event emitter?

The EventEmitter. call(this) , when executed during Dog instance creation, appends properties declared from the EventEmitter constructor to Dog . Remember: constructors are still functions, and can still be used as functions. Oh, so it is just the constructer of EventEmitter?

Which of the following class is required to raise and handle custom events?

Node. js uses events module to create and handle custom events. The EventEmitter class can be used to create and handle custom events module.

What is an event emitter in node js explain with an example?

Many objects in a Node emit events, for example, a net. Server emits an event each time a peer connects to it, an fs. readStream emits an event when the file is opened. All objects which emit events are the instances of events.


1 Answers

Yes, it is.

Before Node 0.10, it wouldn't break if you forget that.

Now, it will:

The EventEmitter constructor initializes various properties now. It still works fine as an OOP inheritance parent, but you have to do inheritance properly. The Broken-Style JS inheritance pattern will not work when extending the EventEmitter class. This inheritance style was never supported, but prior to 0.10, it did not actually break.

like image 50
SLaks Avatar answered Sep 21 '22 20:09

SLaks