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?
可以将文章内容翻译成中文,广告屏蔽插件可能会导致该功能失效(如失效,请关闭广告屏蔽插件后再试):
问题:
回答1:
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
回答2:
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);
}
};
回答3:
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.