views:

415

answers:

3

I have some elements with events bound. Before I remove those elements, do I need to unbind them first? If I don't will they cause problems?

Thanks.

Edit: I realized I phrased the question incorrectly, so now I'm making an edit, excuse me for that, I but I think it makes more sense to do this than make a new question.

I would have to use unbind or remove on an element if I replace it, right? With the js replacewith method or html method in jquery.

+1  A: 

No, it won't cause any problems whatsoever (unless someone has an unpleasant experience they would like to share :) My money is on 'it matters not!'.

The only exception I can think of is if you're doing any live event binding, in a situation where you wouldn't want newly inserted elements to get the same event handlers of the elements you previously removed from the DOM. Then it would be a good idea to unbind any (live) event handlers prior to removal from the DOM, that said, you can do that at any stage, and not necessarily prior to removal.

karim79
thank you
Jourkey
+6  A: 

No, you don't need to do that (event unbinding is done automatically at removal).

Eran Betzalel
+3  A: 

The only time that you would need to explicitly unbind would be if you no longer wanted an event handler for an event on the page.

Removing an element from the DOM causes the events and data for that element to be removed too. Here is the relevant source code

remove: function( selector ) {
 if ( !selector || jQuery.filter( selector, [ this ] ).length ) {
  // Prevent memory leaks
  jQuery( "*", this ).add([this]).each(function(){
   jQuery.event.remove(this);
   jQuery.removeData(this);
  });
  if (this.parentNode)
   this.parentNode.removeChild( this );
 }
}
Russ Cam
thanks +1
Jourkey