Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Do I need to unbind jquery event before remove element?

I have a page using jquery-ui-dialog. Each time the dialog opens, page contents load in using ajax. Then it binds some event using jquery "on()". When the dialog close, it will empty its content.

The question is, do I need to unbind the events on ".ajax-content" before $.empty()?

edit: concern 1. any possible degrade JS performance? if I empty() hundreds of nodes this way.

concern 2. would remove element also remove events from memory(or whatever execution/evaluation chain of jquery)?

I am not doing anything to them for now. If the dialog open/close for many times without page refresh, would it cause any problem?

Code look like this:

<div id="jquery-dialog" class="container">   <div class="ajax-content">     some buttons....   </div> </div>  ------after each ajax load------------ $(".ajax-content").on("click", ".button", function(event) {   //handles the click });  ------on dialog close------------ $("#jquery-dialog").empty(); 
like image 772
Reed Avatar asked Jun 09 '12 01:06

Reed


People also ask

Does jQuery remove unbind events?

jQuery unbind() MethodThe unbind() method removes event handlers from selected elements. This method can remove all or selected event handlers, or stop specified functions from running when the event occurs.

What is bind and unbind in jQuery?

jQuery bind() function is used to attach an event handler to elements, while the unbind() is used to detached an existing event handler from elements.

How do I remove a Click event from an element?

The removeEventListener() is an inbuilt function in JavaScript which removes an event handler from an element for a attached event. for example, if a button is disabled after one click you can use removeEventListener() to remove a click event listener.

Which function is used to remove an existing event handler?

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


1 Answers

Hey I know this is an old question but I believe the accepted answer is misleading.

Although it's correct to say that you will need to unbind events on raw JS to avoid memory leaks on old browsers (ehem IE), calling remove() or empty() will already do that for you.

So your current call to empty() should be enough, it doesn't need to be preceded by unbind()

From jQuery docs (http://api.jquery.com/empty/)

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

like image 157
Oscar Avatar answered Sep 23 '22 18:09

Oscar