Scenario
How to implement the "ajaxStart" effect on a specific request?
First of all, the cost of overriding the Ajax method is too high. You can still make use of jQuery's own Ajax Events.
Global events triggered by Ajax will be propagated to all DOM nodes like a standard event. Level: jQuery Events > Ajax Events > Custom Ajax events.
Implementation
Wo = window.Wo || { };
Wo.ajax = {
spinner : $([])
,init : function() {
var $spinner = this.spinner = $('#ajax-loading') ;
var show = function(e) {
if(e.namespace === 'Wo') $spinner.show();
};
var hide = function(e) {
$spinner.hide();
};
$spinner.bind({
'ajaxStart.Wo' : show
,'ajaxStop.Wo' : hide
,' ajaxError.Wo' : hide
});
this.adapt(['getJSON','get','post','ajax']);
}
// Prepare to send request
,_prepare : function() {
this.spinner.trigger('ajaxStart.Wo');
}
//Interface batch change
,adapt : function(fns) {
var self = this;
$.each(fns,function(i,fn) {
Wo[fn] = function() {
self._prepare();
$[fn ].apply(this,arguments);
}
});
}
};
There are two ways to determine whether the triggered event is specific Events for:
Determined namespace.
Pass additional parameters to the event handler when triggered.
The namespace of the event is used here to determine the trigger source. The adapt method is equivalent to the application of an adapter, replacing another set of interfaces with an improved interface.
If you want to add a load method, it is a little more troublesome, because it may be the ajax method or the onload event of the element.
To add a proxy method and perform type judgment:
var _load = $.fn.load;
$.fn.load = function() {
$.type(arguments[0]) === 'string' && self._prepare();
_load.apply(this,arguments);
return this;
};
Using
all method parameters are still the same as before:
Wo.post(url, [data,] callback)