JQuery clone () does not clone event bindings, even with on ()

I created a series of custom jQuery events for use in mobile web applications. They work great and have been tested. However, I had a small problem that I had problems with understanding.

I use .clone() for several elements inside the DOM that contain a button. The button has some user events associated with it (events are bound using .on() ), but. Unfortunately, when I use jQuery .clone() , the bindings are not saved, and I have to add them again.

Has anyone come across this before, does anyone know of a potential job? I thought using .on() supposed to preserve the binding for elements that exist now or in the future?

+87
javascript jquery
Mar 03 '12 at 20:35
source share
2 answers

I think you should use this method overload . clone () :

 $element.clone(true, true); 

clone ([withDataAndEvents] [, deepWithDataAndEvents])

withDataAndEvents : A Boolean value that indicates whether event handlers and data should be copied along with the elements. The default value is incorrect.

deepWithDataAndEvents : A Boolean value indicating whether to copy event handlers and data for all children of the cloned element. By default, its value corresponds to the first argument (the default value is false).




Remember that .on() does not actually associate events with goals, but with the element to which you are delegating. Therefore, if you have:

 $('#container').on('click', '.button', ...); 

Events are actually tied to #container . When a .button element is .button , it bubbles up to the #container element. The element that triggered the event is evaluated by the .on() selector parameter, and if it matches, an event handler is executed. This is how event delegation works.

If you clone the #container element, you need to deeply clone events and data for the bindings made using .on() to save.

This would not be necessary if you used .on() for the parent of #container .

+188
Mar 03 2018-12-12T00:
source share

You should know that deep cloning functionality has been added to jQuery version 1.5.

Additional information on this topic:

http://api.jquery.com/clone/

+4
Jun 07 '13 at 8:38
source share



All Articles