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');
o => some-thing happened only from the same object but not another. Why? And how to make them both to listen some event?events.EventEmitter.call( this ); line does? It doesnt make any difference to result. Taken from http://nodejs.org/api/util.html#util_util_inherits_constructor_superconstructorThey 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.
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);
having a response
o => some-thing happenedonly 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
someevent?
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?