raineorshine
12/14/2015 - 10:22 PM

The Simplest Event Emitter

The Simplest Event Emitter

// super simple event emitter
function Emitter() {

  var subscribers = [];

  return {
    on: function (name, f) {
      subscribers.push({
        name: name,
        f: f
      });
    },

    trigger: function (name, data) {
      subscribers
        .filter(function (subscriber) {
          return subscriber.name === name;
        })
        .forEach(function (subscriber) {
          subscriber.f(data);
        });
    }
  };
}