Events and the Event Emitter
Events
Something that has happened in our app that we can respond to.
Two kinds:
System Events:
C++ side libuv
file reading / data from internet
Custom Events:
Inside js core
Self created
Event emitter
Not real, faked
Building Our Own Event Emitter
emitter.js
function Emitter() {
this.events = [];
}
Emitter.prototype.on = function(type, listener) {
// check if existing
this.events[type] = this.events[type] || [];
// add to container
this.events[type].push(listener);
};
Emitter.prototype.emit = function(type) {
if (this.events[type]) {
this.events[type].forEach(function(listener) {
listener();
})
}
}
module.exports = Emitter;
app.js
var Emitter = require("./emitter.js");
var emtr = new Emitter();
emtr.on('greet', function() {
console.log('listener envoked1');
});
emtr.on('greet', function() {
console.log('listener envoked2');
})
console.log("hello")
emtr.emit('greet');
// hello
// listener envoked1
// listener envoked2
The point of an emitter.
Do something when something happens. In our case, we waited for console.log(), and then manually invoked the emitter with keyword greet.
Better design to encapsulate an Emitter object, rather than having if and else statements.
The Node Event Emitter
The node api has this built in library.
It has the same basic concept of above, and it will have the same output:
var Emitter = require("events");
var emtr = new Emitter();
emtr.on('greet', function() {
console.log('listener envoked1');
});
emtr.on('greet', function() {
console.log('listener envoked2');
})
console.log("hello")
emtr.emit('greet');
Using the Event Emitter
Dont use magic numbers or strings
e.g. constants with special meanings
So instead, it would become better practice to encapulate our type of events within our own modules.
module.exports = {
events: {
GREET: 'greet',
FILEOPENED: 'file opened',
FILECLOSED: 'file closed'
}
}
and envoke them like this:
var Emitter = require("events");
var configEvents = require("./config.js").events;
var emtr = new Emitter();
emtr.on(configEvents.GREET, function() {
console.log('listener envoked1');
});
emtr.on(configEvents.GREET, function() {
console.log('listener envoked2');
})
console.log("hello")
emtr.emit('greet');
Inheriting From the Event Emitter
Last updated
Was this helpful?