I wrote some javascript to run through an array of "modules". For each module it makes an ajax call, gets the html for the module, and dumps the module into one of two columns on the page layout.
var modules = [
{ name: 'ExchangeStatus', title: 'Exchange Status', column: 'left' },
{ name: 'Grid', title: 'Contacts', column: 'right' }
{ name: 'Filters', title: 'Filters', column: 'left' }
],
modulesUrl = '/Modules/';
for (var count = 0; count < modules.length; count++) {
var module = modules[count];
// Get module HTML.
$.ajax({
url: modulesUrl + module.name,
success: function (moduleHtml) {
// Append module HTML to appropriate element.
$('#' + module.column + 'Column').append(moduleHtml);
// Custom event to trigger the module to load its data.
var initializeModuleEvent = $.Event('initialize' + module.name);
initializeModuleEvent.firstLoad = true;
$(document).trigger(initializeModuleEvent);
}
});
}
Problem with this is that the for loop creates a race condition. In the ajax callback module.column
is almost always the value of the last module because the for loop finishes long before the ajax callbacks return. How can I maintain the module variable so that each callback is dealing with the appropriate module? Currently all three modules end up in the left column because the last module in the loop is in the left column.