The Node Event Emitter - Part 1

Big Word

Event Listener: The code that responds to an event.

In javascript's case, the listener will be a function.

The code

app.js

var Emitter = require('./emitter');

var emtr = new Emitter();

emtr.on('greet', function() {
    console.log('Somewhere, someone said hello.');
});

emtr.on('greet', function() {
    console.log('A greeting occurred!');
});

console.log('Hello!');
emtr.emit('greet');

emitter.js

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]) {
        this.events[type].forEach(function(listener) {
            listener();
        });
    }
}

module.exports = Emitter;
  • See, we gave it a fancy name, but it's just Javascript
  • Understand the code above before you continue

results matching ""

    No results matching ""