-
-
Save SunboX/3ad98781eab0e9d34585ec01d96994ec to your computer and use it in GitHub Desktop.
Backbone Sync Queue
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) -> | |
type = (options.type or 'get').toLowerCase() | |
# 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() | |
# For GET requests, the order is not terribly important. | |
# The `requestPending` flag is not since it does not deal with | |
# saving changes to the server. | |
if type is 'get' | |
sendRequest options, promise, false | |
else if requestPending | |
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