I am developing a web application with dynamic content loading.
In my code, I have a main container div (<div id="container"/>
) where I use AJAX
to load HTML content.
// function overwritten by loadMenu functions
// called before loading a new section
function unbindPreviousSection() { };
// method to load contacts menu
function loadContactsMenu() {
unbindPreviousSection();
unbindPreviousSection = function () { };
$.get("/Home/Contacts", function (data, status) {
if (status === "success") {
$("#content").html(data);
contactsMenu.bind();
unbindPreviousSection = contactsMenu.unbind;
}
});
};
// load profile menu
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;
};
}());
Within each menu load function, I internally invoke the unbind
method of the previously loaded menu.
loadContactsMenu();
loadProfileMenu(); // internally calls contactsMenu.unbind();
Prior to loading any data, I utilize the unbindPreviousSection()
function to clear out the previous menu data.
Now, my query is:
Even after setting it to null, does the viewModel
variable inside the contactsMenu
object still linger in memory after calling contactsMenu.unbind()
? Could this potentially lead to memory leaks?
Does the contactsMenu.addPhone
function create a closure that retains the viewModel
variable in memory since it's used within the function?