【问题标题】:How can I detect when all Backbone ajax requests are complete?如何检测所有 Backbone ajax 请求何时完成?
【发布时间】:2016-04-26 20:06:15
【问题描述】:

我可以使用 jQuery 查看每个完成的时间,但我需要 all 主干 ajax 请求的开始和结束。

这样我就可以向用户展示并指示用户知道该应用正在运行。

我可以将每个请求推送并弹出到一个数组中,但想知道是否有更简单的方法?

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

这是一种解决方案:

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

【问题讨论】:

    标签: javascript ajax backbone.js


    【解决方案1】:

    我使用了一个依赖于 Backbones 内置事件的简单模式。我主要将它用于我的视图以显示/隐藏加载图标。在下面的示例中,我发送了 2 个请求。在每个请求成功时,我都会增加一个计数器。如果该计数器达到 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(){
    
        }
    })
    

    【讨论】:

    • 注意:waitToLoad 被定义为原型属性 - 此实现不适用于多个 View 实例,也不适用于两次或更多。为了支持这个waitToLoad应该在initialize()中初始化
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-02-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-07-17
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多