Skip to content

Instantly share code, notes, and snippets.

@soutaro
Created March 18, 2013 18:11
Show Gist options
  • Save soutaro/5189411 to your computer and use it in GitHub Desktop.
Save soutaro/5189411 to your computer and use it in GitHub Desktop.
class AjaxQ
initialize: (options) ->
_.extend(this, Backbone.Events)
@options = _.clone(options)
_.extend(@options, max:3)
@waiting = []
@requests = []
enqueue: (k) ->
this.trigger("enqueue")
@waiting.push(k)
this.consume()
push: (k) -> this.enqueue(k)
consume: () ->
return this unless @requests.length < @options.max
return this unless @requests.length > 0
this.trigger("consume")
k = @waiting.shift()
xhr = k()
@requests.push(xhr)
xhr.complete () =>
index = _.indexOf(@requests, xhr)
# Check if the queue is aborted
delete @requests[index] if index >= 0
setTimeout (=> this.consume()), 10
abort: () ->
this.trigger("aborting")
$.Deferred (dfd) =>
for xhr in @requests
xhr.abort()
@requests = []
@waiting = []
this.trigger("aborted")
setTimeout (=> dfd.resolve()), 10
dfd
hasRunningRequest: () -> @requests.length > 0
hasWaitingRequest: () -> @waiting.length > 0
isEmpty: () -> not(this.hasRunningRequest()) and not(this.hasWaitingRequest())
window.AjaxQ = AjaxQ
@queue = new AjaxQ(max:6)
@queue.enqueue => @model.fetch()
@queue.enqueue => @collection.fetch()
@queue.enqueue => @account.save()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment