patternjavascriptMinor
Making sure all elements are processed in a JQuery call
Viewed 0 times
elementsallaresurecalljquerymakingprocessed
Problem
I have a piece code similar to below:
But I keep having this nagging feeling that there has to be an easier way!
Any ideas?
But I keep having this nagging feeling that there has to be an easier way!
Any ideas?
var synch = false
var indexArray = new Array();
var rowCount = theTable.find('tr').length;
$(".views").each(function(index) {
indexArray.push( $(this).val()); // Not the real code but something to this effect
if (rowCount <= (index+1)) synch = true;
});
while (!synch);
DO something with indexArray.....Solution
There is absolutely no need for the
(By the way, that function you have there can be rewritten for greater efficiency)
Let's assume that you are doing something async in that each loop, for instance, ajax calls. Your best bet is to keep a count of how many of the calls are completed in the callback function, then execute the rest of your code when the last callback function is called:
This can be abstracted away into another function, though doing that is left as an exercise for the reader.
synch part - JavaScript is synchronous, and you should not get into a situation where the processing of that function (the one you're showing) will not be completed before the next line runs. (By the way, that function you have there can be rewritten for greater efficiency)
var indexArray = $('.views').map(function(){
return this.value;
}).get();Let's assume that you are doing something async in that each loop, for instance, ajax calls. Your best bet is to keep a count of how many of the calls are completed in the callback function, then execute the rest of your code when the last callback function is called:
var views = $('.views'),
completed = 0,
total = views.length;
views.each(function(){
someAsyncFunction (function(){
// Process data
if(++completed === total) {
// We're done! Let's move on..
}
});
});This can be abstracted away into another function, though doing that is left as an exercise for the reader.
Code Snippets
var indexArray = $('.views').map(function(){
return this.value;
}).get();var views = $('.views'),
completed = 0,
total = views.length;
views.each(function(){
someAsyncFunction (function(){
// Process data
if(++completed === total) {
// We're done! Let's move on..
}
});
});Context
StackExchange Code Review Q#617, answer score: 3
Revisions (0)
No revisions yet.