documentcloud/backbone — pull request #1325 by rpflorence (2012-05-16 19:48:35+00:00)
Title: abort pending requests in Backbone.sync

Sending a pull request to start a conversation, happy to make adjustments to my branch if the team feels like this is a valid patch.

### Purpose

It's not uncommon to have user interaction trigger a collection.fetch or model.fetch. Imagine a user clicking several filters for a list of items, or a search field fetching results as the user types. Usually the requests sent all come back in the right order--but not always.

Consider this:

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

The solution is to cancel the pending request.

### Commit Message

when collection.fetch is called multiple times
(perhaps due to user-interaction with the page)
an earlier request could land _after_ a later
request, causing unexpected state in the app

this commit tracks the last requests across all
collections and models and their sync methods,
checks if its pending, and aborts it.

can be overridden with `{safe: false}` in the sync
options object