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?
Backbone is known for being lightweight, as its only hard dependency is on one JavaScript library, Underscore. js, plus jQuery for use of the full library. It is designed for developing single-page web applications, and for keeping various parts of web applications (e.g. multiple clients and the server) synchronized.
BackboneJS provides various building blocks such as models, views, events, routers and collections for assembling the client side web applications. When a model changes, it automatically updates the HTML of your application. BackboneJS is a simple library that helps in separating business and user interface logic.
You can use the Backbone. Model without jQuery, but Backbone.
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
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); } };
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With