I have the following code:
for (var i=0; i < 20; i++) {
var itemButton = $('<button />').click(function(){ alert('Hello'); }).append('Hello');
$('#container').append(itemButton);
}
Where i create lots of buttons each with a onclick function. Then i clear the #container using $('#shopSearchTopBar').empty(); and create the buttons again.
My question is: Is this a possible memory leak? Does Javascript frees the memory used for those anonymous functions i created the first time when i call the .empty() method on the #container or the memory gets freed an i can safely add those 20 new buttons each with his own new anonymous function?
2 Answers 2
Those functions are stored in jQuery.cache.
As long as you use jQuery methods like .empty(), that data will be cleaned up for all affected elements.
If you did something like this:
document.getElementById('container').innerHTML = '';
Then you'd likely have a pretty nasty memory leak because the connection between each element and jQuery.cache would be severed and that data (and likely more) would be sitting orphaned in the cache.
Stick to the jQuery methods when removing/overwriting content, and you'll be fine.
Even when doing this:
$('#container').html('');
...jQuery will clean up that data for affected elements.
5 Comments
If all the anonymous function does is show an alert, then I'd define the function outside the loop, and reference it by name. That way, it'll only get created once, instead of 20 times.
var clickHandler = function(){ alert('Hello'); };
for (var i=0; i < 20; i++) {
var itemButton = $('<button />').click(clickHandler).append('Hello');
$('#container').append(itemButton);
}
It's different if it makes use of closures, but that doesn't seem to be the case here.
4 Comments
this gets assigned when the function is called. Ultimately when you assign a handler to several elements like this $('.someElements').click(function(){}), jQuery is doing effectively the same thing, using a shared reference to the function among the different elements.
bindandclickfor assigning handlers..click(fn)is just a wrapper for a call to.bind('click',fn), so I don't understand how the bind version shortens this code. There are other uses of bind where it can shorten a bit, but they don't really relate to the question.