Search code examples
javascriptbackbone.jsmemory-leaks

Circular reference memory leak?


I am in doubt if the following design pattern would cause a memory leak.
I have been using it for some time with success, but I haven't seen this pattern used by others, so I'd like some confirmation if you see something wrong with it.
As from next month I have to start working on a large project, and I want to know for sure that I can use this without problems, or if I should use another strategy.

controller.js:

var Controller = function(options){ 
}; 

Controller.prototype.makeView = function(options){ 
    options.controller = this; 
    options.otheroption = options.otheroption; 
    var view = new View(options); 
}; 

Controller.prototype.getModel = function(options){ 
    //--- Get model --- 
    var model = new Model(); 
    var promise = model.fetch(); 
    return promise; 
}); 

view.js:

var View = Backbone.View.extend({ 
    initialize: function(options){
        this.controller = options.controller; 
        this.otheroption = options.otheroption; 
    }, 
    getModel: function(){ 
        var promise = this.controller.getModel(); 
        promise.done(_.bind(function(model){
            //Do something with the returned model instance 
        }, this)); 
    }; 
}); 

Instantiate controller, eg. from the router, or another controller:

//--- Instantiate the controller and build the view ---// 
var controller = new Controller(); 
controller.makeView(options)

To me, this doesn't look like a circular reference, because both the controller and view are declared as a local variable. Yet the instantiated view can access the controller functions, which allows me to isolate the RESTful server interactions via models / collections that the view uses.

For me it would seem as if the only reference remaining would be the view that keeps a reference to the controller object. What I do afterwards is clean up the view (I destroy the instance and its references when I don't need it anymore.

Your opinion on this pattern is highly appreciated.
My purpose is to isolate creation of views / server interactions in separate controller files: if you see holes in my method and have a better way of doing it, please share.

Thanks.


Solution

  • Short answer: There is no memory leak problem in the code you have posted. The view holds a reference to the controller, but not vice versa. So as long as the controller lives longer than the view, that reference does not keep your objects from being garbage-collected. I don't see a circular reference anywhere in your code.

    Longer answer: The pitfalls would be in the code you haven't posted. In particular, any event handlers in your view must be cleaned up properly, otherwise your views never fade into oblivion. But you have said in your question that you clean up your view, so I guess you are aware of that sort of problem.