Search code examples
javascriptbackbone.jsxmlhttprequestbackbone-eventsjqxhr

How to Access XHR Object When Making AJAX Requests with Backbone's Fetch()?


Within a backbone app, I am making a call with fetch when a users takes a certain action:

 changeDay: function() {
  this.collection.fetch({
    success: function() {
      lr.primaryView.addAllEvents();
    }
  });
 },
 ...

Sometimes, a user takes actions that calls this changeDay method again before the first request has successfully responded. In these cases, I want to cancel the previous request. I am familiar with how to do this with vanilla jQuery (it is outlined here) but I am unable to easily use that approach here since the XHR object is hidden behind fetch. How can I solve this?


Solution

  • Backbone.fetch actually returns the jQuery XHR object:

     changeDay: function() {
      thisXHR = this.collection.fetch({
        success: function() {
          lr.primaryView.addAllEvents();
        }
      });
     },
     ...