Skip to content

Commit

Permalink
Fix bug on loading multiple plugins
Browse files Browse the repository at this point in the history
  • Loading branch information
pauloborges committed Feb 9, 2015
1 parent 2b95766 commit 2764674
Showing 1 changed file with 31 additions and 43 deletions.
74 changes: 31 additions & 43 deletions mapbox.js
Original file line number Diff line number Diff line change
Expand Up @@ -124,59 +124,42 @@ var FILES = {
var deps = new Deps.Dependency;
var loaded = false;

var loadCount = 0;
var loadCallback = null;

var pluginCount = 0;
var plugins = null;

var onLoaded = function () {
loaded = true;
deps.changed();
};

var onPluginLoaded = function () {
pluginCount--;

if (pluginCount == 0)
onLoaded();
};
var onMapboxLoaded = function (plugins, cb) {
var pluginCount = _.size(plugins);

var onMapboxLoaded = function () {
pluginCount = _.size(plugins);

if (pluginCount == 0) {
onLoaded();
if (pluginCount === 0) {
cb();
return;
}

_.each(plugins, function (pluginName) {
var plugin = FILES[pluginName];
var loadCb = function () {
pluginCount--;

if (plugin)
loadFiles(plugin, onPluginLoaded);
else
console.log('Invalid MapBox plugin: "' + pluginName + '"');
});
};

var onLoadedFile = function (url) {
if (Mapbox.debug)
console.log('Loaded "' + url + '"');
if (pluginCount === 0) {
cb();
return;
}

loadCount--;
plugin = plugins.shift();
loadFiles(FILES[plugin], loadCb);
};

if (loadCount == 0)
loadCallback();
var plugin = plugins.shift();
loadFiles(FILES[plugin], loadCb);
};

var loadScript = function (src) {
var loadScript = function (src, cb) {
var elem = document.createElement('script');
elem.type = 'text/javascript';
elem.src = src;
elem.defer = true;

elem.addEventListener('load', _.partial(onLoadedFile, src), false);
elem.addEventListener('load', _.partial(cb, src), false);

var head = document.getElementsByTagName('head')[0];
head.appendChild(elem);
Expand All @@ -192,17 +175,22 @@ var loadCss = function (href) {
};

var loadFiles = function (files, cb) {
loadCount = _.size(files.js);
loadCallback = cb;
var loadCount = _.size(files.js);

_.each(files.css, function (url) {
loadCss(url);
});
var loadCb = function (url) {
if (Mapbox.debug)
console.log('Loaded:', url);

loadCount--;

if (loadCount === 0)
cb();
};

_.each(files.css, loadCss);
_.each(files.js, function (url) {
loadScript(url);
loadScript(url, loadCb);
});

};

Mapbox = {
Expand All @@ -212,8 +200,8 @@ Mapbox = {
if (loaded)
return;

plugins = _.values(arguments);
loadFiles(FILES.mapbox, onMapboxLoaded);
var plugins = _.values(arguments);
loadFiles(FILES.mapbox, _.partial(onMapboxLoaded, plugins, onLoaded));
},

loaded: function () {
Expand Down

0 comments on commit 2764674

Please sign in to comment.