0

Trying to make an object emitting and receiving events:

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

function Obj(){
  events.EventEmitter.call( this ); // what does this line?
}

util.inherits( Obj, events.EventEmitter );

var o = new Obj(),
    a = new Obj();

a.on('some', function () {
  console.log('a => some-thing happened');
});

o.on('some', function () {
  console.log('o => some-thing happened');
});

o.emit('some');
Brian Tompsett - 汤莱恩
  • 5,753
  • 72
  • 57
  • 129
Nik Terentyev
  • 2,270
  • 3
  • 16
  • 23

2 Answers2

0
  1. They are separate event emitting objects, the only thing inherits() does is sets the prototype of the subclass to be that of the prototype of the parent. Subclasses are not magically linked together.

  2. events.EventEmitter.call( this ); executes the parent's constructor to allow it to perform some initialization of its own (for example, setting up the event listeners object that stores event handlers for events and other properties). Then after events.EventEmitter.call( this ); you can perform your own initialization for your subclass on top of that. This typically includes properties that are instance specific (e.g. this.id = Math.random() * 1000);

mscdex
  • 104,356
  • 15
  • 192
  • 153
0

having a response o => some-thing happened only from the same object but not another. Why?

Because they're different emitter objects. Each emitter notifies only its own listeners; it's an observer pattern not a mediator one.

And how to make them both to listen some event?

Use only a single EventEmitter instance. You might not even need that Obj subclass, just do a = o = new EventEmitter().

What events.EventEmitter.call( this ); line does? It doesnt make any difference to result.

See What is the difference between these two constructor patterns?

Community
  • 1
  • 1
Bergi
  • 630,263
  • 148
  • 957
  • 1,375
  • Observer means that you are listening to a specific observable - and you have two of them, only one of them is emitting an event. Mediator would mean that you have a global object on which all others are listening and/or firing events. – Bergi Oct 03 '14 at 10:07