Jquery empty function and event handlers

The jQuery documentation of the "empty" function (http://api.jquery.com/empty/) has 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 elements! CH i LD! ...". But I want event handlers to also be removed from the div tag ($ ("# mydiv"). Empty). I know that there is a “delete” function, but I intend not to remove the div tag. What is the best way to do this?

Another thing:
When they say "delete event handlers." Do they only delete constructs created using bind, or do they also delete constructs created using bind?

Thanks in advance

+6
source share
3 answers

To remove all related 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 talks about handlers for related events, not delegated ones, because they are associated with an ancestor element (or the document itself) that is not affected by deletion.

This allows delegated handlers to continue to work as intended if the deleted item is restored later.

+8
source

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(); 
+1
source

If I read correctly, you do not want the div tag to be deleted, you just want to delete all the data and handlers in this case, combine .empty () with:

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

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

Use the delete tool appropriate to how you bind the events.

If you want the called element to be deleted, do not use .empty (), use .remove () instead.

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

"Like the .empty () method, the .remove () method accepts elements from the DOM. Use .remove () when you want to remove the element itself, as well as everything inside it. For the elements themselves, all related events and jQuery data related with elements are deleted.To delete elements without deleting data and events, use .detach () instead.

0
source

Source: https://habr.com/ru/post/921109/


All Articles