Search code examples
javascriptjquerysuperagent

SuperAgent equivalent of Jquery's ajaxStart ajaxStop


My team is currently trying to get rid of our jQuery. We've managed to get rid of all our selectors, and are in the process of refactoring it out of our ajax calls, but we're trying to recreate the ajaxStart and ajaxStop functions.

I've been looking through the SuperAgent docs, and I'm unable to find anything equivalent to this. Does anyone know of something similar to this in SuperAgent or know how to recreate this with event listeners or something?

My alternative is just to add display changes directly to each request, which is 200ish lines I'd like to avoid.

window.onload = function() {
  $(document)
  .ajaxStart(function(){
    document.getElementById('ajaxSpinner').style.display = 'block';
  })
  .ajaxStop(function(){
    document.getElementById('ajaxSpinner').style.display = 'none';
  });
}

Edit: We have figured out how to use the accepted answer in our code base. We have moved the code in the selected answer into its own module that we are requiring wherever we use SuperAgent. On each of our calls we are now including .use(Module.stats). So far this solution appears to work, however we haven't started cross browser testing yet. Thanks for your help!

Edit2: Occassion required us to rebuild the app. The accepted answer does not work with the most recent version of SuperAgent, we had to roll it back to version 1.7.2.


Solution

  • https://github.com/visionmedia/superagent/issues/861#issuecomment-173413292

    hope the link above is helpful

    quote code:

    function stats(req) {
        req.once('request', function() {
            // ajaxstart
            req._startedAt = Date.now();
        });
        req.once('error', function() {
            // an error,the request fail
        });
        req.once('end', function() {
            // ajaxstop
            var use = Date.now() - req._startedAt;
        });
    }
    
    function get(url) {
        return request.get(url)
            .use(stats);
    }
    
    Request.prototype._end = Request.prototype.end;
    Request.prototype.end = function(fn) {
        this.emit('request');
        this._end(fn);
    }