Created
April 27, 2012 08:16
-
-
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.
This file contains hidden or 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
// 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) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
i wanted to control how many times saving is delayed to prevent loosing big sets of client-side changes.