Pergunta

I have objects who's only references are the DOM elements they are tied to and I'm not sure if calling $element.remove() actually removes the reference or just the DOM element. Here's some example code.

var Foo = function() {
    var constructor = function Foo() {
        var col = '#'+(Math.random()*0xFFFFFF<<0).toString(16);
        var $container = $('<div class="element" style="background-color:'+col+';"></div>');
        var $remove = $('<input type="button" value="Delete" />');
        $container.append($remove);
        $('#wrapper').append($container);

        $remove.on('click', function() {
            $container.remove();
        });
    };
    return constructor;
}();

$('#addElement').on('click', function() {
    new Foo();
});

And a jsfiddle for people to play around with. Click one button to add elements, click each element's "Delete" button to remove it; from the DOM at least.

It's not necessarily a problem for my current project because of the small scale, but I think it'd be really useful to know for future reference if I'm ever working on something large.

If it doesn't, is there any way to remove the objects without holding them in some array?


EDIT: Ok, so I've kinda answered my own question using the chrome heap snapshots and adding 10,000 elements to the page. Here's the important data. (I've included HTMLInputElements because the majority of what I'm inserting are those)

                Initial         10,000          Removed
Memory          2.7MB           135MB           4.0MB
Objects         1,676           81,693          11,703
InputElements   1               59,995          1

So yeah, it seems that the garbage collector is smart enough to remove the objects when the DOM element referencing them is removed. Though it's not perfect.

Foi útil?

Solução

The objects will be garbage collected as soon as you do not have a reference to the object anymore. I'm not sure if it would be considered a "best practice" to do this though. From MDN:

On the other hand, JavaScript values are allocated when things (objects, strings, etc.) are created and "automatically" free'd when they are not used anymore.

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Memory_Management

The "automatically" described above in modern browsers means that objects that are considered "unreachable" will be marked for garbage collection.

Calling $.element.remove() will only remove the DOM element because it only knows about the DOM element. It's not possible that it could remove any other object associated with the DOM element because it does not know about that object.

http://api.jquery.com/remove/

Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top