Is it possible to stop Backbone “read” requests

2019-02-03 02:00发布

I have a backbone application that has a number of views. Switching between views triggers Ajax requests to get different collections. I would like to stop the current "read" ajax request if a new one is started. Is it possible?

3条回答
兄弟一词,经得起流年.
2楼-- · 2019-02-03 02:25

I assume you're using backbone with jQuery. If so, the following question seems to provide an answer for you:

Abort Ajax requests using jQuery

Backbone fetch returns the xhr they're talking about, IIRC.

查看更多
Anthone
3楼-- · 2019-02-03 02:30

Ok so here is what I did

I am saving the the fetch requests in a variable

app.fetchXhr = this.model.fetch();

In my router, I have a function that takes care of closing the views and rendering views. It also takes care of triggering any triggers needed for each view change but that is not relevant in this question.

Before doing anything, this router function executes the following

//Stop pending fetch
if(app.fetchXhr.readyState > 0 && app.fetchXhr.readyState < 4){
    app.fetchXhr.abort();
}

I hope this helps

查看更多
等我变得足够好
4楼-- · 2019-02-03 02:42

Yet another late reply in case someone else runs into this.

I ended up overwriting Backbone.sync to add a XHR object pool and an option to abort pending requests on fetch.

var sync = Backbone.sync
  , xhrPool = [];

Backbone.sync = function(method, model, options) {
  options = options || {};
  if (method === 'read') {
    if (options.abortPending == true) {      
      for (var i = 0; i < xhrPool.length; i++) {
        if (xhrPool[i]['readyState'] > 0 && xhrPool[i]['readyState'] < 4) {
          xhrPool[i].abort();
          xhrPool.splice(i, 1);
        }
      }
    }

    // cleanup xhrPool
    // todo: make removal from the pool an 'always' jqXHR callback
    // instead of cleanup on every read?
    for (var i = 0; i < xhrPool.length; i++) {
      if (xhrPool[i]['readyState'] === 4) {
        xhrPool.splice(i, 1);
      }
    }

    var xhr = sync(method, model, options);
    xhrPool.push(xhr);
    return xhr;
  } else {
    return sync(method, model, options);
  }
};
查看更多
登录 后发表回答