Home > Web Front-end > JS Tutorial > Code to use jQuery global event ajaxStart to implement prompt effects for specific requests_jquery

Code to use jQuery global event ajaxStart to implement prompt effects for specific requests_jquery

WBOY
Release: 2016-05-16 18:13:06
Original
1047 people have browsed it

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

Copy code The code is as follows:

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:
Copy the code The code is as follows:

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:
Copy code The code is as follows:

Wo.post(url, [data,] callback)
Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template