Catalin
Catalin

Reputation: 11721

Javascript clearing objects from memory after AJAX load

I am implementing a single page application.

I have a container div (<div id="container"/>), where i load html content using AJAX.

// function that is overwritten by loadMenu functions
// and gets called before loading a new section 
function unbindPreviousSection() { };

// load contacts
function loadContactsMenu() {
    unbindPreviousSection();
    unbindPreviousSection = function () { };

    $.get("/Home/Contacts", function (data, status) {
        if (status === "success") {
            $("#content").html(data);
            contactsMenu.bind();
            unbindPreviousSection = contactsMenu.unbind;
        }
    });
};

// load profile
function loadProfileMenu() {
    unbindPreviousSection();
    unbindPreviousSection = function () { };

    $.get("/Home/Profile", function (data, status) {
        if (status === "success") {
            $("#content").html(data);
            unbindPreviousSection = function() {
                // specific unbind methods for this menu
            };
        }
    });
};

var contactsMenu = {};
(function () {
    var viewModel = null;

    contactsMenu.bind = function () {
        viewModel = {
            phones: ko.observableArray()
        };
    };

    contactsMenu.addPhone = function (phone) {
        viewModel.phones.push(phone);
    };

    contactsMenu.unbind = function () {
        viewModel = null;
    };
}());

Inside any menu load function, i internally call unbind method of the previous loaded menu.

loadContactsMenu();
loadProfileMenu();  // internally calls contactsMenu.unbind();

Before i load any data, i call unbindPreviousSection() function to dispose the previous menu data.

My question is:

Is viewModel variable inside contactsMenu object still persisting after i call contactsMenu.unbind() even if i set it to null? (does it creates memory leaks?)

Does contactsMenu.addPhone function creates a closure which saves in memory viewModel variable (because is used inside the function)?

Upvotes: 0

Views: 138

Answers (1)

alehro
alehro

Reputation: 2208

  • Variable viewModel is just a reference to object. After you set viewModel to null the object it's referencing becomes eligible to garbage collection (i.e. becomes not persisting), unless you have other references to the object.
  • Closures hold objects in memory only until the owner function is running. In other words, Closure starts referencing it's objects at the start and releases references at the end. Regarding addPhone function it means that practically it doesn't keep viewModel's object in memory.

I'd recommend to use Chrome profiler to check this and any further memory leak problems. You can take memory snapshot there and see for every object who is holding it in memory.

Upvotes: 1

Related Questions