簡體   English   中英

如何檢測所有Backbone ajax請求何時完成?

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

我可以使用jQuery查看每一個完成的時間,但是我需要所有主干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;
  };

我使用了一個簡單的模式,該模式依賴於事件內置的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(){

    }
})

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM