Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does jQuery's replaceWith() also remove event handlers?

Tags:

jquery

I've looked through the jQuery Documentation for the answer to this simple question:

Does replaceWith() call remove() or detach() under the hood?

I've had no luck with the official documentation; it is ambiguously defined as removing the node. But tests show a memory leak.

like image 562
Claude Houle Avatar asked Oct 19 '11 15:10

Claude Houle


People also ask

Which function is used to remove an existing event handler?

The removeEventListener() method removes an event handler from an element.

Should I remove event listeners before removing elements?

Removing the event listener first always results in lower memory usage (no leaks). Results: IE6 - memory leak.


2 Answers

Looking at the source code of jQuery (2.1.1), you're asking two different questions.

  1. Does jQuery's replaceWith() remove event handlers?

    Yes. jQuery calls cleanData(), which is an internal method which removes all data on an element. Since jQuery event handlers are stored in the elements data, they will also get cleaned up.

    cleanData() also removes the event handler attached to the element which triggers the execution of all event handlers stored in the elements data, by calling jQuery.removeEvent() (another internal method).

  2. Does replaceWith() call remove() or detach() under the hood?

    The only time it calls remove() is if no arguments were provided to replaceWith(); jQuery treats it as if you were calling remove() instead of replaceWith();


TL;DR: jQuery will clean everything up for you, so there shouldn't be a risk of memory leaks.

like image 79
Matt Avatar answered Sep 18 '22 15:09

Matt


FYW if you don't want that behavior take a look a this poorly discussed thread over jQuery tickets http://bugs.jquery.com/ticket/13400

and for those who wont ready expect code, here's an implementation of the replaceWith that uses detach instead of remove

with remove()

old.replaceWith( new );

with detach()

old.before( new ).detach();

like image 32
aemonge Avatar answered Sep 19 '22 15:09

aemonge