I have a function which binds different form inputs
function bindInputs() {
$(".inputContainer").each(function(i){
var inputContainer = $(this),
input = $("input.input", inputContainer),
inputType = inputContainer.attr("data-inputType"),
input_Id = inputContainer.attr("id").replace("inputContainer_", "");
if(inputType == "TextEditor") {
input.unbind("change").bind("change", function() {
inputContainer.removeClass("nullValue");
var value = input.val();
saveInputValue(input_Id, value);
});
return true;
}
if(inputType == "NumericEditor") {
input.numeric({ allow: "." });
input.unbind("change").bind("change", function() {
inputContainer.removeClass("nullValue");
var value = getNumericValue(input.val());
saveInputValue(input_Id, value);
});
}
// so on
});
};
Is this function creating memory leaks? The thing i am worried about is that i keep all the shared variables on top and use them inside “change” callback functions.
Would make a difference if i re-calculate the shared variables on the callback functions?
if(inputType == "TextEditor") {
input.unbind("change").bind("change", function() {
var elem = $(this),
inputContainer = elem.closest(".inputContainer"),
input_Id = inputContainer.attr("id").replace("inputContainer_", "");
inputContainer.removeClass("nullValue");
var value = input.val();
saveInputValue(input_Id, value);
});
return true;
}
It’s not creating leaks. It is preserving those variables in memory for as long as those functions are in memory.
Whether you want to do that is up to you, it’s a trade-off. For a
changehandler, the overhead of re-querying the DOM is minimal so you might go with your second example, although the actual memory impact of what you’re retaining in that example is fairly minimal. In amousemovehandler, you’d probably go the other way, becausemousemovehandlers need to do their work very quickly.Re your question in the comments below:
If you’re going to make the functions not rely on anything in the
bindInputsfunction, define them outside of it entirely. Then you’re not creating any closures at all over the context of the call tobindInputs, and that context can be GC’d (along with any variables it contains). Setting variables tonullorundefinedjust sets them tonullorundefined, it doesn’t get rid of them. (Although at that point, the context containing them is pretty small. Just three or four vars that don’t reference anything in particular.)Here’s what that might look like: