Search code examples
javascriptnode.jseventsevent-handlingeventemitter

One object doesn't listen to an event emitted on another object


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');

Solution

  • 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?