Skip to content

Instantly share code, notes, and snippets.

@andris-silis
Created April 27, 2012 08:16
Show Gist options
  • Star 5 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save andris-silis/2507358 to your computer and use it in GitHub Desktop.
Save andris-silis/2507358 to your computer and use it in GitHub Desktop.
extended backbone.js sync function. uses setTimeout to batch multiple saves on one model in one http request.
// decreases request count on rapid-fire one model saves
// extended backbone.js sync function. uses setTimeout to batch multiple saves on one model in one http request.
// if client side needs immediate answer from server for changes in model attributes,
// pass { immediate: true } in model save options if { wait: true } is not used already.
Backbone._sync=Backbone.sync
Backbone.sync = function(method, model, options){
var maxResetCount=5 // how many times to delay save
var saveBufferSize=3000 // for how many microseconds save is delayed
var immediate=options['wait'] || options['immediate'] || false
// init state variables
if (!_.has(this, 'saveQueue')){
this.saveQueue={}
}
if (!_.has(model, 'saveResetCount')){
model.saveResetCount=0
}
var args=arguments,
self=this
// work only on update requests,
// because it works safely only on idempotent requests and delete usually is invoked only one time ;)
if (method==='update' && immediate!==true){
// if model is in save queue, remove old timeout - it will be replaced by new one
if (_.has(this.saveQueue, model.id)){
model.saveResetCount+=1
if (model.saveResetCount<maxResetCount){
console.debug('Backbone.sync: clearing timeout. reset count='+model.saveResetCount)
clearTimeout(model.saveTimeoutId)
}else{
console.debug('Backbone.sync: NOT clearing timeout. reset count='+model.saveResetCount)
}
}else { // if model is not in save queue, place it in it
console.debug('Backbone.sync: placing model in save queue')
this.saveQueue[model.id]=model
}
if (model.saveResetCount<maxResetCount){
model.saveTimeoutId=setTimeout(
function(){
console.debug('Backbone.sync: delayed sync')
delete self.saveQueue[model.id]
model.saveResetCount=0
Backbone._sync.apply(self, args)
},
saveBufferSize
)
}
}else{
return Backbone._sync.apply(self, args)
}
}
@subimage
Copy link

subimage commented May 3, 2012

Instead of using setTimeout you could use the underscore.js "debounce" function fyi...

@andris-silis
Copy link
Author

i wanted to control how many times saving is delayed to prevent loosing big sets of client-side changes.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment