I would like to register a global ajaxSuccess handler, which would upon certain conditions cancel the specific ajaxSuccess handler of the caller functions.
Is there a way to achieve this?
Thanks in a开发者_StackOverflow社区dvance
Unfortunately there's not a way to do what you're after, not that way, you'll have to set a global variable or something some other route. If you look at how the jQuery success function works:
handleSuccess: function( s, xhr, status, data ) {
// If a local callback was specified, fire it and pass it the data
if ( s.success ) {
s.success.call( s.context, data, status, xhr );
}
// Fire the global callback
if ( s.global ) {
jQuery.ajax.triggerGlobal( s, "ajaxSuccess", [xhr, s] );
}
}
You can see it's just a matter of ordering, the local success
handler always happens before the global event is fired, which triggers any $.ajaxSuccess()
handlers. The easiest way to do what you're after is to call whatever function may cancel at the beginning of your local success
handler, like this:
$.ajax({
//options...
success: function(data) {
if(shouldIBeCanceled()) return;
//rest of code...
}
});
The alternative is editing jQuery core, or extending it which will yield somewhat unpredictable behavior for plugins, so I wouldn't go down that route, as it's likely to also introduce a new pain when upgrading as well.
精彩评论