How do I fake AJAX start / end events in JQuery?

javascript, jquery

Solution

According to the sources you just need to invoke:

jQuery.event.trigger( "ajaxStart" );

and

jQuery.event.trigger( "ajaxStop" );

correspondingly.

http://jsfiddle.net/zerkms/7RVbz/

Problem

I'm listening to ajaxStart() and ajaxStop() to show/hide a spinner, and I'm doing some mock AJAX stuff in JS while servers are being written. It just calls a function to generate mock data with a setTimeout(). For now I'm just manually calling hide() and show() on the spinner, but I'd really like to just tell JQuery when I'm starting and stopping my "request", and have the events go through that way, so I don't accidentally hide() the spinner while a real ajax request is still going in the background. Can this be done easily? EDIT: This is the code I settled on, the trick is maintaining the `JQuery.active` count: ``` function fakeAJAX(f) { if(jQuery.active++ === 0 ) { jQuery.event.trigger("ajaxStart"); } setTimeout(function () { f(); if(!(--jQuery.active)) { jQuery.event.trigger("ajaxStop"); } }, Math.round(Math.random() * 3000 + 250)); } ```

Original source