0

我的团队目前正试图摆脱我们的 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:有时需要我们重建应用程序。接受的答案不适用于最新版本的 SuperAgent,我们不得不将其回滚到 1.7.2 版本。

4

1 回答 1

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);
}
于 2016-01-21T01:30:42.813 回答