Reputation: 51
I am very new to JavaScript and NodeJS, I was just trying to understand the emitter pattern in NodeJS. When I try to emit a tick event every second, using the setInterval
function, the program seems to be working fine:-
var util = require('util'),
EventEmitter = require('events').EventEmitter;
var Ticker = function() {
var self = this;
setInterval(function() {
self.emit('tick');
}, 1000);
};
util.inherits(Ticker, EventEmitter)
var ticker = new Ticker();
ticker.on('tick', function() {
console.log('TICK');
});
But, when I try to emit an event without using the setInterval
method, my event is not being called:-
var util = require('util'),
EventEmitter = require('events').EventEmitter;
var Ticker = function() {
var self = this;
self.emit('tick');
};
util.inherits(Ticker, EventEmitter)
var ticker = new Ticker();
ticker.on('tick', function() {
console.log('TICK');
});
Please help, I don't understand, where I am wrong...
As far as my understanding, when self.emit
is called, ticker.on
is not registered, and hence the event is missed. If this is the case, how do I emit an event when an object is created?
Upvotes: 2
Views: 2474
Reputation: 501
The fact is that you need someone to emit the event. It can be a function, setInterval, setTimeout etc..
The usage of event emitter is only to bind all those functions, to be called when a given event is emitted by someone..
Hence you will always need someone to emit events.
Upvotes: 1
Reputation: 14866
how do I emit an event when an object is created
You already know the answer. Just listen to that event before triggering it. There is no other solutions. Asynchronously firing emit
is just a messier one. And also, I don't recommend writing ES5 on nodejs.
let Event = require('event');
class Ticker extends Event{
constructor(){
super();
this.on('tick', () => {
console.log('TICK');
});
this.emit('tick');
}
}
new Ticker();
// or better
class Ticker extends Event{
constructor(){
super();
}
}
var ticker = new Ticker();
ticker.on('tick', () => {
console.log('TICK');
});
ticker.emit('tick');
Upvotes: 1
Reputation: 174937
JavaScript is a (mostly*) synchronous language, unless otherwise specified, code runs from top to bottom, and only asynchronous events are queued for later.
Without the setInterval queuing the emit()
for later, you have something like this:
create Ticker
Ticker.emit()
Ticker.on(...)
So basically, the .emit()
happens synchronously, and before the first call to .on()
.
*Mostly because with ES2015 we have Promises, which are a language-level construct for describing something asynchronous, that's not important, however, for the problem you're observing.
Upvotes: 1