Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

When emptying a tag, do the event-attached-buttons inside get garbage collected?

Having a code like this, I'm wondering if I ran this function a second time, which scenario will happen:

  1. When emptying the #deals tag, all btn inside will get wiped as well despite the event on them and life is good.
  2. I have to unsubscribe from those btn first, otherwise emptying the #deals tag leads to a memory leak?
  3. List item

Code:

function test(){
    var row = $(this).closest('tr');  
    $(row).find('#deals').empty();

    $(result).find('#tab li a').each(function() {               
      var btn = $('<a/>', {class: 'btn', href: '#'});

      $(row).find('#deals').append(btn);

      btn.click(function(event){
          event.preventDefault();
          ...
         });
    });
}
like image 761
Houman Avatar asked Dec 20 '12 10:12

Houman


People also ask

Are event listeners garbage collected?

Yes. The reference is being removed behind the scenes and the garbage collection also happens behind the scenes. It is a good idea to remove event listeners when you don't need them. Apps that keep recreating event listeners without removing them is a potential source of memory leaks.

How do you know if an object is garbage collected?

You normally can't tell whether an object has been garbage collected by using some reference to the object–because once you have a reference to the object, it won't be garbage collected. You can instead create a weak reference to an object using the WeakReference object.

How does garbage collection work in Unity?

The Garbage Collector in Unity is an automatic process that safeguards against memory leaks by removing unused data from the heap. When the managed heap fills up, meaning that there isn't a space big enough for a new allocation of data, the garbage collector will run to try to make room for it.

Which step do you perform to prevent an object from being garbage collected?

We have three ways to achieve same - 1) Increasing the Heap -Eden space size . 2) Create Singleton class with Static reference . 3) Override finalize() method and never let that object dereference.


2 Answers

You don't have to unsuscribe :

To avoid memory leaks, jQuery removes other constructs such as data and event handlers from the child elements before removing the elements themselves.

(from the documentation)

like image 169
Denys Séguret Avatar answered Oct 05 '22 22:10

Denys Séguret


No memory leak.

As you can see in jQuery source, it takes care of cleaning everything up.

like image 30
Florian Margaine Avatar answered Oct 06 '22 00:10

Florian Margaine