Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it possible to stop Backbone "read" requests

Tags:

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?

like image 928
Xerri Avatar asked Oct 05 '12 15:10

Xerri


People also ask

What is backbone used for?

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.

How backbone js works?

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.

Does backbone need jQuery?

You can use the Backbone. Model without jQuery, but Backbone.


2 Answers

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

like image 73
Xerri Avatar answered Oct 04 '22 08:10

Xerri


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);   } }; 
like image 41
Garrett Johnson Avatar answered Oct 04 '22 07:10

Garrett Johnson