Reputation: 7736
If I have click
event listener on many dynamically created elements, will they use the memory when remove()
is called by removeEventListner
is not?
Say I have some code like this:
for (var i = 0; i < 9999; i++) {
var $btn = $('<button class="my_button">');
$('body').append($btn);
$btn.click(function(){ /* ... */ })
}
$('.my_button').remove();
Will the event handlers still use memory? Do I have to call removeEventListner
if I want to make sure there's no memory leak risk?
Upvotes: 1
Views: 67
Reputation: 337550
The memory held by that element will be released when it is removed from the DOM and destroyed. This is handled by the browser, so although there in theory shouldn't be any memory leaks you are at the mercy of the garbage collector.
That being said there's a much better approach you can use here. Create a single delegated event handler on a parent element of all the buttons. Then you have one event handler instance which works for all button elements. This will save memory and mean you don't need to worry about the specifics of any garbage collection when removing elements from the DOM. Try this:
$('#buttonContainer').on('click', '.my_button', function() {
// button click action here...
});
Upvotes: 2