Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jquery empty function and event handlers

Tags:

jquery

In the jquery documentation of the "empty" function (http://api.jquery.com/empty/) there is the following statement:

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

The text says: "... jQuery removes event handlers from the !C H I L D! elements ...". But I want the event handlers also removed from the div tag ($("#mydiv").empty). I know that there is the function "remove", but my intention is to not remove the div tag. What is the best way to get this done?

The other thing is:
When they say "remove event handlers". Do they only remove constructs made with "bind" or do they also remove constructs made with "delegate"?

Thanks alot in advance

like image 855
Wolfgang Adamec Avatar asked Jul 23 '12 08:07

Wolfgang Adamec


3 Answers

To remove all bound event handlers from an element, you can pass the special value "*" to the off() method:

$("#mydiv").empty().off("*");

When the documentation says remove events handlers, it only speaks of bound event handlers, not delegated ones, since these are bound to an ancestor element (or the document itself) which is not impacted by the removal.

This allows delegated handlers to keep working as intended if the removed element is reinstated later.

like image 59
Frédéric Hamidi Avatar answered Nov 12 '22 01:11

Frédéric Hamidi


If i read correctly you do not want the div tag removed, you just want to remove all data and handlers in that case combine the .empty() with:

http://api.jquery.com/unbind/

However note that: "Event handlers attached with .bind() can be removed with .unbind(). (As of jQuery 1.7, the .on() and .off() methods are preferred to attach and remove event handlers on elements.) In the simplest case, with no arguments, .unbind() removes all handlers attached to the elements:"

Use the removal tool that corresponds with the way you're binding events.

If you want the element you're calling removed as well don't use .empty(), use .remove() instead.

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

"Similar to .empty(), the .remove() method takes elements out of the DOM. Use .remove() when you want to remove the element itself, as well as everything inside it. In addition to the elements themselves, all bound events and jQuery data associated with the elements are removed. To remove the elements without removing data and events, use .detach() instead."

like image 44
Eirinn Avatar answered Nov 12 '22 02:11

Eirinn


try this jQuery code;

 jQuery('#element').bind('click',function(){
    console.log('clicked');
    }).on('remove',function(){
       console.log('element removed');
       jQuery(this).unbind('click').off('remove');
    });

    jQuery('#element').remove();
like image 1
Haydar C. Avatar answered Nov 12 '22 01:11

Haydar C.