Jump To …

util.js

(function (global) {

var util = (function () {
  var that = {};

  function eventify (o) {
    var eventListeners = {};

    function addEventListener (name, cb) {
      if (typeof eventListeners[name] === 'undefined') {
        eventListeners[name] = [];
      }
      eventListeners[name].push(cb);
    }

    function removeEventListener (name, cb) {
      var i, iMax, theseEventListeners = eventListeners[name];
      if (theseEventListeners) {
        for (i=0,iMax=theseEventListeners.length; i<iMax; i++) {     
          if (theseEventListeners[i] === cb) {

theseEventListeners.splice(i, 1); this is a kludge so that event listeners can remove themselves, otherwise the loop over the listeners in event() will break. Thinking this is probably more efficient than using an Object instead of an Array, which would also work.

            theseEventListeners[i] = function () {};
            break;
          }
        }
      }
    }

    function removeEventListeners (name) {
      delete eventListeners[name];
    }

    function event (name, e) {
      var i, iMax, theseEventListeners = eventListeners[name];
      if (theseEventListeners) {
        e = e || {};
        e.type = name;
        for (i=0,iMax=theseEventListeners.length; i<iMax; i++) {     
          theseEventListeners[i](e);
        }
      }
    }

    o.addEventListener = addEventListener;
    o.removeEventListener = removeEventListener;
    o.removeEventListeners = removeEventListeners;
    o.event = event;

    return o;
  }

  that.eventify = eventify;

  return that;
}());


if (typeof module != 'undefined' && module.exports) {
  module.exports = util;
} else {
  global.trurl = global.trurl || {};
  global.trurl.util = util;
}

}(this));