8

If an element is removed from the page, does it automatically unbind? Or is this a scenario in which one ought to unbind using jquery's unbind?

I assume it's done automatically...

Matrym
  • 16,643
  • 33
  • 95
  • 140
  • @martym when you remove a elment from the dom and do a page load again , then it won't bind again as it cannot find that element. it happens on the next page load. – kobe Dec 05 '10 at 00:22
  • Why would I be doing another page load, without a refresh? I'm a little confused by your answer... – Matrym Dec 05 '10 at 00:25

1 Answers1

6

If you remove elements using remove or empty, event handlers will automatically be removed in order to prevent memory leaks. Otherwise they will remain, unless they are explicitly unbinded prior to removing those elements.

EDIT: Turns out .html will remove event handlers too, by calling an internal .cleanData method (declared on line 5177). You can check this in the source:

html: function( value ) {
   ...

    for ( var i = 0, l = this.length; i < l; i++ ) {
                    // Remove element nodes and prevent memory leaks
                   if ( this[i].nodeType === 1 ) {
                       jQuery.cleanData( this[i].getElementsByTagName("*") );
                       this[i].innerHTML = value;
                    }
                }
   ...

So, to avoid memory leaks, don't directly use innerHTML to replace DOM elements which have attached jQuery event handlers.

karim79
  • 339,989
  • 67
  • 413
  • 406
  • So if I replace the contents of a div using .html("stuff"), am I to understand that the elements previously inside it remain bound? Can I unbind afterwards, or do I have to unbind before removing them from the dom? – Matrym Dec 05 '10 at 00:23
  • @karim79 just for learning purposes can you give one example of a memory leak related to binding elements...to click or mouseover – kobe Dec 05 '10 at 00:24
  • @martym .html apply's html to some existing dom elemnts so there is no need to bind agian , if the elements which are going needs to have some binds then you have to use jquery.live and do it. – kobe Dec 05 '10 at 00:25
  • @Matrym - When you call `unbind`, it searches the DOM for elements matching the selector it was called on, so no, you cannot unbind afterwards. – karim79 Dec 05 '10 at 00:25
  • @Karim, thanks, that's what I figured. @GOV, I think you misunderstand me. If doms are bound and then removed from the page by having their parent's container's HTML changed, it sounds like the bindings will persist and consist of a memory leak. – Matrym Dec 05 '10 at 00:28
  • @martym i misunderstood , sorry. – kobe Dec 05 '10 at 00:34
  • normally when we want to disable any clicks or any otherevents we use unbind....i was under that impression. – kobe Dec 05 '10 at 00:34