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

  • 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:

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.

and envoke them like this:

Inheriting From the Event Emitter

Last updated

Was this helpful?