In a Node.js-based project, I have a couple objects:
EmitterA
EmitterB
Consumer
In Consumer
's constructor, I have the following:
var a = new EmitterA();
a.on('someEvent', someEventHandler);
In EmitterA
's constructor, I have the following:
var self = this;
var b = new EmitterB();
b.on('someEventFromB', function() {
self.emit('someEvent');
});
Finally, in EmitterB
's constructor, I have something like this:
this.emit('someEventFromB');
The problem is that Consumer
's someEventHandler()
doesn't get fired when the inital .emit()
from EmitterB
is fired. The reason is one of timing. Consumer
doesn't subscribe to someEvent
on EmitterA
until after the event has been fired.
Is there a way to attach event handlers at the time of construction? I have considered utilizing the newListener
event, but this will be problematic when working with multiple listeners later on, and situations where there are many different types of events that will be fired. I'd like to avoid this route if possible, and am looking for alternatives that you may suggest. Thanks!
try something like:
var a = new EmitterA({
events : {
someEvent : someEventHandler
}
});
function EmitterA( props ){
props || ( props = {} );
if( props.events ){
for( var n in props.events ){
this.on( n, props.events[n] );
}
}
// the rest of the constructor code
}
I just thought of an alternate way that works for my specific case, but may be problematic for others. Please use it with a grain of salt.
In EmitterB
's constructor, I changed this.emit('someEventFromB');
to this:
process.nextTick(function() {
this.emit('someEventFromB');
}
See also: http://howtonode.org/understanding-process-next-tick