Dispatch events in JavaScript I needed a simple and efficient way to use events in my JavaScript code, so I came up with a small event library.

Currently, I'm doing it like this:

// eva.js - The lightweight es6 event library.
var eva = (() =&gt; {
  // Prepare local globals
  var eva = {};
  var receivers = [];
  var gid = 0;
  /**
   * Verify the type of a parameter.
   * Throw if the type does not match the expected type.
   * @param {object} item - The argument itself
   * @param {string} name - The name of the argument
   * @param {string} expected - The expected type
   */
  var verifyType = (item, name, expected) =&gt; {
    if (typeof (item) !== expected) {
      throw "Argument '" + name + "' has to be of type '" + expected + "'.";
    }
  }
  /**
   * Subscribe to an event.
   * @param {string} name - The name of the event
   * @param {function} action - The event action
   * @returns {number} - The subscription identifier
   */
  var subscribe = (name, action) =&gt; {
    verifyType(name, 'name', 'string');
    verifyType(action, 'action', 'function');
    receivers.push({name: name, action: action, id: gid});
    return gid++;
  }
  /**
   * Unsubscribe from an event.
   * @param {number} id - The subscription identifier
   * @returns {boolean} - Whether the subscription has been removed
   */
  var unsubscribe = id =&gt; {
    verifyType(id, 'id', 'number');
    var result = false;
    receivers.every((item, index, arr) =&gt; {
      if (item['id'] === id) {
        arr.splice(index, 1);
        result = true;
      }
      return !result;
    });
    return result;
  }
  /**
   * Dispatch an event.
   * @param {string} name - The name of the event
   * @param {object} e - The event data
   */
  var dispatch = (name, e) =&gt; {
    verifyType(name, 'name', 'string');
    receivers
      .filter(item =&gt; name === item['name'])
      .forEach(item =&gt; item['action']({event: name, data: e}));
  };
  /**
   * List all receivers.
   * @returns {array} - The receivers
   */
  var list = () =&gt; receivers;
  /**
   * Clear all receivers.
   */
  var clear = () =&gt; {
    receivers.length = 0;
  };
  // Make functions accessible
  eva.subscribe = subscribe;
  eva.unsubscribe = unsubscribe;
  eva.dispatch = dispatch;
  eva.clear = clear;
  eva.list = list;
  // Return eva object
  return eva;
}());
module.exports = eva;


Since I usually don't write JavaScript code and don't know any best practices and quirks of that language, constructive criticism would be greatly appreciated.
It's not bad, though there are some things I'd do different.

Firstly, I'd use a map of arrays for receivers. Doesn't have to be a Map instance, a simple object literal will do. For instance, subscribe would look like this:

var receivers = {};

var subscribe = (name, callback) =&gt; {
  if(typeof callback === 'function') {
    receivers[name] = (receivers[name] || []);
    receivers[name].push(callback);
  } else {
    throw new TypeError("callback must be a function");
  }
}


This makes it simple to dispatch events:

var dispatch = (name, data) =&gt; {
  receivers[name].forEach(receiver =&gt; receiver({name: name, data: data}));
}


Secondly, I wouldn't use rely on a gid value to track receivers; I'd use the receiver itself. It eliminates needing to track multiple IDs if one function is subscribing to multiple events, and it makes the sub/unsub functions "symmetrical": All you need is an event name and a function.

function someHandler() { ... }

eva.subscribe('someEvent', someHandler);
eva.unsubscribe('someEvent', someHandler);


To achieve this, unsubscribe could look like:

var unsubscribe = (name, callback) =&gt; {
  if(receivers[name]) {
    receivers[name] = receivers[name].filter((receiver) =&gt; receiver !== callback);
  }
}


Also, one important note: Your list function returns a reference to the receivers array. I don't know if this is intended, but it does mean, that you'd be modify the otherwise-"private" array. For instance, saying eva.list().push("foobar") will cause problems, because it sidesteps all you type-checking, and adds something to the array that your code isn't expecting.

Frankly, I don't know how useful the list function is to begin with, but in your current code, you could halfway fix the issue by simply calling slice() on the receivers array. That'll create a copy, and return that instead:

var list = () =&gt; receivers.slice();


However, the contents of the copied array will be references to the same objects that are in "private" receivers array, so you cause mischief:

eva.list()[0].action = "foobar"; // obviously not a proper callback


You could spend the time doing a deep clone of everything, but... eh.

Again, simpler to let the array only contain functions. Even if they're returned as references in a copied array, it's harder to accidentally break things.

If you use an object/map to hold the receivers as I suggest above, you do have to do some more complex cloning to return it safely (although the arrays it contains can be copied safely with slice). However, I'd just scope everything in the API to a name, including list and clear:

var list = (name) =&gt; receivers[name] ? receivers[name].slice() : [];

var clear = (name) =&gt; receivers[name] = [];


If you want to could add a method to return all registered event names by using Object.keys(receivers).

You'll note that I haven't bothered much with type-checking. Only when subscribing do I check that the callback is actually a function. But name arguments? Don't really care.

Type-checking isn't super necessary in JS. Often it really doesn't matter due to type coercion, or you explicitly cast/parse if you need to. Other times it's just simpler to say "garbage in, garbage out": If someone really wants to use a float as an event name, let them. And let them sort it out, if things don't work. This is what I usually lean toward. Since JS isn't strictly typed (and sometimes plain weird), the effort spent implementing your own type-checking could be spent better elsewhere.

All together, minus comments:

var eva = (() =&gt; {
  var receivers = {};

  var subscribe = (name, callback) =&gt; {
    if(typeof callback === 'function') {
      receivers[name] = (receivers[name] || []);
      receivers[name].push(callback);
    } else {
      throw new TypeError("callback must be a function");
    }
  }

  var unsubscribe = (name, callback) =&gt; {
    if(receivers[name]) {
      receivers[name] = receivers[name].filter((receiver) =&gt; receiver !== callback);
    }
  }

  var dispatch = (name, data) =&gt; {
    receivers[name].forEach(receiver =&gt; receiver({name: name, data: data}));
  }

  var list = (name) =&gt; receivers[name] ? receivers[name].slice() : [];

  var clear = (name) =&gt; receivers[name] = [];

  return {
    subscribe: subscribe,
    unsubscribe: unsubscribe,
    dispatch: dispatch,
    list: list,
    clear: clear
  };
}());