I've got some IDS that I want to use to fill / generate some jQuery Objects. I use these IDS in ajax requests. After the jQuery Objects have been filled, I want to sort them.
Has to work in IE11.
What my problem is: At the moment I've no idea how the best practice would look like, to wait for all ajax requests and as well all jQuery objects to be filled.
- I have to wait until all ajax requests have been completed (so always, indepedent from response code (so on .done and .fail))
- I have to wait until all jQuery Objects are filled with the results from the ajax Requests
Problem conclusion: sort function is called before the items are filled.
I've tried to break down my whole code to a simple example, maybe someone can help here:
function sortEntries(a, b) {
var aa = ($(a).data('name') || '').toLowerCase(),
bb = ($(b).data('name') || '').toLowerCase();
return aa < bb ? -1 : aa > bb ? 1 : 0;
}
function getEntryInfo(infoObj, callback) {
function getLabelByResult(result) {
var name = '';
switch (result) { // For this demo, we don't use the response data.
case 'page-header':
name = 'Hello World 1';
break;
case 'thumbnails':
name = 'It works!';
break;
case 'nav':
name = 'Great!';
break;
case 'btn-groups':
name = 'BTN GROUP';
break;
default:
name = 'NOT SET!'
}
return name;
}
return $.ajax({
method: 'GET',
url: infoObj.URI,
cache: false
}).done(function(data) {
if ($.isFunction(callback)) {
callback(true, {
name: getLabelByResult(infoObj.element)
});
}
}).fail(function() {
if ($.isFunction(callback)) {
callback(false, {
name: getLabelByResult(infoObj.element)
});
}
});
}
function setInfoForEntry(item$, config) {
return getEntryInfo(config, function(isOk, responseObjInfo) {
item$.attr('data-name', responseObjInfo.name || '').text(responseObjInfo.name || '');
});
}
function generateItems() {
var parentItem$ = $('body').append($('<ul/>').addClass('allItems').hide()),
ids = ['page-header', 'thumbnails', 'nav', 'btn-groups'], // for testing purposes of course
requests = [],
extractedItems$;
$.each(ids, function(ignorel, el) {
var newItem$ = $('<li/>').addClass('idItem').on('click', function(e) {
alert($(e.currentTarget).data('name'));
});
parentItem$.append(newItem$);
requests.push(setInfoForEntry(newItem$, {
URI: 'https://getbootstrap.com/docs/3.3/components/#/' + el,
element: el
}));
});
// HERE I HAVE TO ENSURE THAT:
// -ALL AJAX REQUESTS ARE DONE
// -ALL jQuery Elements are filled
extractedItems$ = parentItem$.find('.idItem');
extractedItems$.sort(sortEntries);
extractedItems$.detach().appendTo(parentItem$);
parentItem$.show();
}
$(document).ready(function() {
generateItems();
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<body></body>