Scenario
How can we achieve "ajaxStart" in a specific request?
First, the price for rewriting Ajax methods is too high, and jQuery's own Ajax Events can still be used.
Global events triggered by Ajax are transmitted to all DOM nodes like a standard event. Level: jQuery Events> Ajax Events> Custom Ajax Events.
Implementation
Copy codeThe 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. work': show
, 'Ajaxstop. work': hide
, 'Ajaxerror. work': hide
});
This. adapt (['getjson', 'get', 'post', 'ajax ']);
}
// Initiate a request
, _ Prepare: function (){
This. spinner. trigger ('ajaxstart. wo ');
}
// API 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 a specific event:
The specified namespace.
When triggered, additional parameters are passed to the event handler.
Here, we use the namespace of the event to trigger the Source Judgment. The adapt method is equivalent to the application of the adapter and replaces another interface with a set of improved interfaces.
If you want to add the load method, it will be a little more troublesome, because it may be an ajax method or an onload event of an element.
You need to add a proxy method and determine the type:
Copy codeThe Code is as follows:
Var _ load = $. fn. load;
$. Fn. load = function (){
$. Type (arguments [0]) === 'string' & self. _ prepare ();
_ Load. apply (this, arguments );
Return this;
};
Use
All method parameters are still consistent with the original one:
Copy codeThe Code is as follows:
Wo. post (url, [data,] callback)