-
-
Save d3chapma/6390235 to your computer and use it in GitHub Desktop.
Removed the assumption about get requests. Added a check if the client is online or not. If not online, just queue the request because we know the request will fail.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# Reference Backbone ajax function | |
_ajax = Backbone.ajax | |
requestQueue = [] | |
requestPending = false | |
sendRequest = (options, promise, trigger=true) -> | |
options = _.clone options | |
if trigger | |
requestPending = true | |
# Reference existing handlers | |
success = options.success | |
error = options.error | |
complete = options.complete | |
# Add custom complete for handling retries for this particular | |
# request. This ensures the queue won't be handled out of order | |
params = | |
complete: (xhr, status) => | |
if complete then complete.apply @, arguments | |
if trigger then dequeueRequest() | |
success: -> | |
if success then success.apply @, arguments | |
promise.resolveWith @, arguments | |
error: -> | |
if error then error.apply @, arguments | |
promise.rejectWith @, arguments | |
# Send request | |
_ajax _.extend options, params | |
# Sends the next request in the queue if one exists | |
dequeueRequest = -> | |
if (args = requestQueue.shift()) | |
[options, promise] = args | |
sendRequest options, promise | |
else | |
requestPending = false | |
# Queues non-GET requests to be executed serially. GET requests | |
# are executed immediately since they are assumed to not have side | |
# effects. | |
queueRequest = (options) -> | |
# Since requests are being queued, the `xhr` is not being created | |
# immediately and thus no way of adding deferred callbacks. This | |
# `promise` acts as a proxy for the request's `xhr` object. | |
promise = $.Deferred() | |
if requestPending || !navigator.onLine | |
requestQueue.push [options, promise] | |
else | |
sendRequest options, promise | |
return promise | |
Backbone.hasPendingRequest = -> | |
requestPending | |
# Override Backbone.ajax to queue all requests to prevent lost updates. | |
Backbone.ajax = (options) -> | |
queueRequest options |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment