简体   繁体   English

如何检测所有Backbone ajax请求何时完成?

[英]How can I detect when all Backbone ajax requests are complete?

I can use jQuery to look at when each completes, but I need the start and the end of all backbone ajax requests. 我可以使用jQuery查看每一个完成的时间,但是我需要所有主干ajax请求的开始和结束。

This is so I can put up and indicator to the the user know that the app is working. 这样一来,我就可以提出建议,并向用户指示该应用程序正在运行。

I could push and pop each request on to an array, but was wondering if there was an easier way? 我可以将每个请求推送并弹出到数组上,但是想知道是否有更简单的方法?

  Backbone.ajax = function() {
    $A.report('BB - ajax called');
    var xhr = Backbone.$.ajax.apply(Backbone.$, arguments); 
    xhr.always(function(){
        $A.report('BB - ajax completed');
    });
    return xhr;
  };

Here is one solution: 这是一种解决方案:

  // Set the default implementation of `Backbone.ajax` to proxy through to `$`.
  // Override this if you'd like to use a different library.
  var requestArray = [];
  Backbone.ajax = function() {
    var xhr = Backbone.$.ajax.apply(Backbone.$, arguments); 
    requestArray.push('mark');
    $A.report('BB - Ajax Started');
    xhr.always(function(){
        requestArray.pop();
        $A.report('BB - Ajax Completed');
        if(requestArray.length === 0){
            $A.report('BB - All Ajax Completed');
        }
    });
    return xhr;
  };

I use a simple pattern that relies on Backbones built in events. 我使用了一个简单的模式,该模式依赖于事件内置的Backbones。 I mainly use this for my Views to show/hide a loading icon. 我主要将其用于视图以显示/隐藏加载图标。 In the example below i send out 2 requests. 在下面的示例中,我发出了2个请求。 On each requests success, I increment a counter. 在每个请求成功时,我增加一个计数器。 If that counter reaches 2, i perform my desired action, which is usually hiding the loading icon and rendering the view. 如果该计数器达到2,我将执行所需的操作,该操作通常是隐藏加载图标并呈现视图。

var exampleView = Backbone.View.extend({
    waitToLoad:0,
    initialize:function(){
        var collection1 = new ExampleCollection();
        var collection2 = new ExampleCollection();
        this.listenTo(collection1,'sync',this.dataReady);
        this.listenTo(collection2,'sync',this.dataReady);
        collection1.fetch();
        collection2.fetch();
    },
    dataReady:function(){
        this.waitToLoad++;
        if(this.waitToLoad == 2){
            //all requests done
            this.render();
            this.waitToLoad = 0;
        }

    },
    render:function(){

    }
})

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM