For one of my backbone project (in which i cannot implement REST/sync), i need to refresh a backbone collection (using backbone relational as model, if it matters ?) every X seconds.
What i've been doing is implement a function like this :
refresh: function(){
var self = this;
// clears timeout
self.timeoutRefresh && clearTimeout(self.timeoutRefresh);
// aborts request if running
self.xhrRefresh && self.xhrRefresh.abort();
// do request
self.xhrRefresh = self.options.myfunction.call(self, {}, function (data) {
self.mycollection.set(data);
// call it again in 5 seconds
self.timeoutRefresh = _.delay(function(){
self.refresh.call(self);
}, 5 * 1000);
});
},
The problem is that this block of code seems to be guilty of a big memory leak in my application.
Can it be a closure problem with the self
variable ?
Should i then do the recursive call this way ?
self.timeoutRefresh = _.delay(function(context){
context.refresh.call(context);
}, 5 * 1000, self);
If not, where does it come from ?
Well after a lot of chrome debugging, i figured out backbone relational was never actually replacing my objects cause it is doing comparison over the id attribute which my objects didn't have (physically and logically).
I ended up calculating a md5 hash from the different meaningful properties of my object and using it as id so backbone relational would know it shouldn't consider the object as a new one.
Conclusion, it's not a closure problem as chrome garbage collector does its thing well.
NB: Backbone debugger helped me a lot finding where the problem came from.