Node Flashcards

1
Q

How does the Event Emitter work?

A

Basically you’re creating “events” as object props, then creating an array on the props where you push functions to. When you “emit” the event, you execute every function in the queue. Ex:

function Emitter() {
  this.events = {};
}

Emitter.prototype.on = function(type, listener) {
this.events[type] = this.events[type] || [];
this.events[type].push(listener);
}

Emitter.prototype.emit = function(type) {
if (this.events[type]) {
for (var listener of this.events[type]) {
listener();
}
}
}

var emtr = new Emitter();

emtr.on(‘greet’, function() {
console.log(‘Somewhere, someone said, Hello’);
});

emtr.on(‘greet’, function() {
console.log(‘good tidings!’);
});

emtr.emit(‘greet’);

How well did you know this?
1
Not at all
2
3
4
5
Perfectly