Reputation: 67131
I have a way of keeping track of current Ajax Requests which involves $.ajaxSetup(), and counting beforeSends & completes.
var ajaxProcs = 0;
$.ajaxSetup({
beforeSend : function () { ajaxProcs++; },
complete : function () { ajaxProcs--; }
});
The problem is, if any given $.ajax() call has beforeSend or complete it will throw off the correct count of Ajax requests running.
For example, this would overwrite it, and not add 1 to the ajaxProcs count.
$.ajax({
beforeSend : function () { /* blah blah */ }
});
Is it possible to have BOTH ajaxSetup AND the $.ajax Override run?
Upvotes: 1
Views: 5175
Reputation: 2615
How about this, let's try beforeSend() function as a sample..
$.ajaxSetup({
beforeSend: function(){
console.log('execute another beforeSend() function');
}
});
Then this is your Ajax function:
$.ajax({
beforeSend : function () {
console.log('execute beforeSend() function');
if('beforeSend' in $.ajaxSettings){
$.ajaxSettings.beforeSend();
}
}
...
And now it will execute the both functions
Hope it helps
Upvotes: 4
Reputation: 411
Try this:
var ajaxProcs = 0;
$(document).ajaxSend(function(){
ajaxProcs++;
});
$(document).ajaxComplete(function(){
ajaxProcs--;
});
This will run on every jQuery ajax call, regardless of what callbacks you bind to the individual requests.
Upvotes: 3
Reputation: 66405
Because of how jQuery is designed I think your best bet is to make a rule to call the ajaxSetup function manually from the beforeSend. Even if jQuery had a more OO approach you would still have to call the parent anyway - it won't magically call itself.
var ajaxProcs = 0;
var setupObj = {
beforeSend : function(xhr) { ajaxProcs++; console.log('Increased to: ' + ajaxProcs); },
complete : function() { ajaxProcs--; console.log('Decreased to: ' + ajaxProcs); }
};
$.ajaxSetup(setupObj);
$.ajax({
url: 'http://fiddle.jshell.net',
beforeSend : function (xhr) {
setupObj.beforeSend(xhr);
}
});
Upvotes: 1
Reputation: 12985
ajaxSetup()
provides default values for parameters that can be passed to the ajax()
function. They only apply as defaults and not when supplied in the actual ajax()
call.
JQuery's ajaxStart()
, ajaxSend()
and ajaxComplete()
are things you might want to read about. They are called before and after each ajax call.
There is a global
option on the individual ajax()
call that will disable those global functions though.
Not really a complete answer because it is overridable but maybe helpful.
Upvotes: 2