SuperAgent相当于Jquery的ajaxStart ajaxStop

时间:2015-10-19 16:51:07

标签: javascript jquery superagent

我的团队目前正试图摆脱我们的jQuery。我们设法摆脱了所有选择器,并且正在从我们的ajax调用中重构它,但我们正在尝试重新创建ajaxStart和ajaxStop函数。

我一直在浏览SuperAgent文档,而且我找不到与此相同的内容。有没有人知道SuperAgent中与此类似的东西,或者知道如何使用事件监听器或其他东西重新创建它?

我的另一种选择就是直接向每个请求添加显示更改,这是我希望避免的200行。

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

编辑:我们已经找到了如何在我们的代码库中使用接受的答案。我们已将选定答案中的代码移动到我们在任何使用SuperAgent的地方都需要的模块中。在我们的每个调用中,我们现在包括.use(Module.stats)。到目前为止,这个解决方案似乎有效,但我们还没有开始跨浏览器测试。 谢谢你的帮助!

Edit2:Occassion要求我们重建应用程序。接受的答案不适用于最新版本的SuperAgent,我们不得不将其回滚到版本1.7.2。

1 个答案:

答案 0 :(得分:2)

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

希望上面的链接有用

引用代码:

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);
}