原生js实现requirejs (阉割版)

function Emitter() {

}

Emitter.prototype.on = function(evtype, fn) {
  this._events = this._events || {};
  this._events[evtype] = this._events[evtype] || [];
  if (this._events[evtype].indexOf(fn) !== -1) return;
  this._events[evtype].push(fn);
}
Emitter.prototype.off = function(evtype, fn) {
  this._events = this._events || {};
  if (evtype in this._events === false)  return;
  fn && this._events[evtype].splice(this._events[evtype].indexOf(fn), 1);
  !fn && delete this._events[evtype];
}
Emitter.prototype.emit = function(evtype, detail) {
  this._events = this._events || {};
  var self = this;
  if (evtype in this._events === false) return;
  this._events[evtype].forEach(function(fn, i) {
      fn.call(self, detail);
  });
}

Emitter.eventify = function(Klass) {
    Klass.prototype = Object.create(Klass.prototype);
    for (var attr in Emitter.prototype) {
        Klass.prototype[attr] = Emitter.prototype[attr]
    }
    return Klass;
}

(function() {
  var cache = {};
  function define(deps, fn) {
    // var emitter = new Emitter();
    var params = [];
    var count = 0;
    var id = document.currentScript.id || 'require_main';
    cache[id] = cache[id] || new Emitter();

    if (deps.length) {
      deps.forEach(function(n, i) {
        count++;
        loadModule(n, function() {
            count--;
            params[i] = cache[n].export;
            if (count === 0) {
                deps_loaded();
            }
        });

      })
    }
    else {
      deps_loaded();
    }

    function deps_loaded() {
        cache[id].export = fn.apply(null, params);
        cache[id].emit('loaded');
      }
  }
  

  function insertScript(id) {
    var s = document.createElement('script');
    s.id = id;
    s.src = id + '.js';
    s.charset = 'utf-8';
    document.getElementsByTagName('head')[0].appendChild(s);
  }

  function loadModule(id, fn) {
    if (cache[id]) {
        cache[id].export ? fn() : cache[id].on('loaded', fn);
    }
    else {
        insertScript(id);
        cache[id] = new Emitter;
        cache[id].on('loaded', fn);
    }
  }
  
  window.define = define;

})();

你可能感兴趣的:(原生js实现requirejs (阉割版))