Skip to content

Commit

Permalink
Rearrange component loader code a bit; I think it's a bit cleaner thi…
Browse files Browse the repository at this point in the history
…s way.
  • Loading branch information
mbest committed Mar 26, 2014
1 parent d64b882 commit 003ea3f
Showing 1 changed file with 15 additions and 20 deletions.
35 changes: 15 additions & 20 deletions src/components/loaderRegistry.js
Original file line number Diff line number Diff line change
Expand Up @@ -25,52 +25,47 @@
}

function ensureComponentIsLoading(componentName) {
var subscribable = getObjectOwnProperty(loadingSubscribablesCache, componentName);
var subscribable = getObjectOwnProperty(loadingSubscribablesCache, componentName),
completedAsync;
if (!subscribable) {
// It's not started loading yet. Start loading, and when it's done, move it to loadedDefinitionsCache.
subscribable = loadingSubscribablesCache[componentName] = beginLoadingComponent(componentName);
subscribable.subscribe(function(definition) {
subscribable = loadingSubscribablesCache[componentName] = new ko.subscribable();
beginLoadingComponent(componentName, function(definition) {
loadedDefinitionsCache[componentName] = definition;
delete loadingSubscribablesCache[componentName];
});
}

return subscribable;
}

function beginLoadingComponent(componentName) {
var loadResultSubscribable = new ko.subscribable(),
completedAsync = false,
notifySubscribersAsync = function(definition) {
// For API consistency, all loads complete asynchronously. However we want to avoid
// adding an extra setTimeout if it's unnecessary (i.e., the completion is already
// async) since setTimeout(..., 0) still takes about 16ms or more on most browsers.
if (completedAsync) {
loadResultSubscribable['notifySubscribers'](definition);
subscribable['notifySubscribers'](definition);
} else {
setTimeout(function() {
loadResultSubscribable['notifySubscribers'](definition);
subscribable['notifySubscribers'](definition);
}, 0);
}
};
});
completedAsync = true;
}

return subscribable;
}

function beginLoadingComponent(componentName, callback) {
getFirstResultFromLoaders('getConfig', [componentName], function(config) {
if (config) {
// We have a config, so now load its definition
getFirstResultFromLoaders('loadComponent', [componentName, config], function(definition) {
notifySubscribersAsync(definition);
callback(definition);
});
} else {
// The component has no config - it's unknown to all the loaders.
// Note that this is not an error (e.g., a module loading error) - that would abort the
// process and this callback would not run. For this callback to run, all loaders must
// have confirmed they don't know about this component.
notifySubscribersAsync(null);
callback(null);
}
});
completedAsync = true;

return loadResultSubscribable;
}

function getFirstResultFromLoaders(methodName, argsExceptCallback, callback, candidateLoaders) {
Expand Down

0 comments on commit 003ea3f

Please sign in to comment.