I have a function that loads a section of a report.
// function to load section
function loadSection(sectionId) {
$.when(
// Now load the specified template into the $overlay.
loadTemplate(sectionId),
// After the template is in place we need to identify all
// the editable areas and load their content.
loadEditables(sectionId)
)
.then(function () {
// Now find all section link elements and wire them up.
buildSectionLinks(),
// Find all hover elements and attach the hover handlers.
loadHovers()
});
}
The idea is that we will load a template, then iterate over the template to find all of the “editables”, which are just user-provided content areas within a template. Once the template and all editables have been loaded we then do some processing over the markup to do things like tie click events to certain elements. All template and editable ajax calls need to be finished before the processing happens.
The call to loadTemplate(sectionId) works just fine with jQuery.when because I’m only doing one ajax call.
// This function goes out to an AJAX endpoint and gets the specified
// report template and appends it to the overlay DIV.
function loadTemplate(sectionId) {
return $.ajax({
url: settings.templateUrl,
data: { sectionId: sectionId },
type: 'post',
success: function (template) {
$overlay.append(template);
}
});
}
The loadEditables(sectionId) function is not as simple to implement because I have to loop through all the editables and do an ajax call for each one.
// This function loads content for all editables defined in the template.
function loadEditables(sectionId) {
// Grab all editables into a jQuery wrapped set.
var $editables = $('#template .editable');
// Loop through each editable and make an AJAX call to load its content.
$editables.each(function () {
var $editable = $(this);
$.ajax({
type: 'post',
url: settings.editableUrl,
data: {
sectionId: sectionId,
editableIndex: $editable.data('editableindex')
},
success: function (editable) {
if (editable.hasData)
$editable.html(editable.content);
}
});
});
}
In loadTemplate I was able to simply return $.ajax(...) in the function to satisfy the $.when(...). In here I’m looping through the wrapped set and doing a new ajax call for each element in the set. How can I make sure all these calls are done before firing the processing functions (buildSectionLinks() and loadHovers())?
Store the promise objects in an array then pass that array to
$.whenusing.apply