Last active
March 21, 2016 07:59
-
-
Save acemir/91c8eac579d7e47570fa to your computer and use it in GitHub Desktop.
Waits multiple ajax calls response
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
var MyRequestsCompleted = (function() { | |
var numRequestToComplete, requestsCompleted, callBacks, singleCallBack; | |
return function(options) { | |
if (!options) options = {}; | |
numRequestToComplete = options.numRequest || 0; | |
requestsCompleted = options.requestsCompleted || 0; | |
callBacks = []; | |
var fireCallbacks = function() { | |
for (var i = 0; i < callBacks.length; i++) callBacks[i](); | |
}; | |
if (options.singleCallback) callBacks.push(options.singleCallback); | |
this.addCallbackToQueue = function(isComplete, callback) { | |
if (isComplete) requestsCompleted++; | |
if (callback) callBacks.push(callback); | |
if (requestsCompleted == numRequestToComplete) fireCallbacks(); | |
}; | |
this.requestComplete = function(isComplete) { | |
if (isComplete) requestsCompleted++; | |
if (requestsCompleted == numRequestToComplete) fireCallbacks(); | |
}; | |
this.setCallback = function(callback) { | |
callBacks.push(callBack); | |
}; | |
}; | |
})(); | |
// Usage | |
var requestCallback = new MyRequestsCompleted({ | |
numRequest: 10, // number of requests | |
singleCallback: function(){ | |
// All fired | |
} | |
}); | |
// After response of each ajax in a loop | |
requestCallback.requestComplete(true); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment