Search code examples
jquerybackbone.jsmarionettebackbone-events

abort all active request before sending another request for same url in backbone collection


i am making search request Consider this:

User Enters "Filter A" for an activity stream. A collection's url changes to represent the filter collection.fetch is called User quickly Enters "Filter B" before the xhr for "Filter A" returns to reset the collection. "Filter B" returns from the server, collection.reset is called automatically for "Filter B" "Filter A" finally returns (after "Filter B") and resets the collection to "Filter A". The app is now in the wrong state.

How do I abort Previous pending request.

self.collection = new searchCollection();
self.collection.fetch({
    timeout : 60000,
    type : 'POST',
    data : {
      "searchString" : searchKey
    },
    beforeSend : function(xhr) {},
    success : function(result) {},
    error : function(xhr, status, error) {}
});

Solution

  • Maintain a variable to save the fetch request.

    self.fetchXhr = self.collection.fetch();
    

    Before placing any fetch request, check whether the variable has valid and ongoing request.

    if(self.fetchXhr != undefined && self.fetchXhr.readyState > 0 && self.fetchXhr.readyState < 4)
       self.fetchXhr.abort();