Wednesday, June 10, 2015

How to prevent events from being bound multiple times

How to prevent events from being bound multiple times

If your Single Page Application is slow or have large DOMs, removing a previously-attached event handler from the elements may help to prevent it being bound twice or few times.

.off( events [, selector ] [, handler ] )

Remove an event handler.

.empty()

Remove all child nodes of the set of matched elements from the DOM.

.remove( [selector ] )

Remove the set of matched elements from the DOM.

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.

.detach( [selector ] )

Remove the set of matched elements from the DOM.

Looping through the direct children:

$("#div1").children().off();
$("#div1").children().empty();

or

$("#div1").children().remove();

Looping through all descendants:

$("#div1").find('*').off();
$("#div1").find('*').empty();

or

$("#div1").remove();

this example .off() is called immediately to ensure previous events (of any kind) with the namespace are un-bound:

$("form")
    .off(".validator")
    .on("keypress.validator", "input[type='text']", validate);

It's quite a flexible API so you can be very specific if you need to be:

$("form")
    .off("keypress.validator", "input[type='text']", validate)
    .on("keypress.validator", "input[type='text']", validate);

Reference:

http://stackoverflow.com/questions/23043234/jquery-off-remove-or-remove-off-performance
http://stackoverflow.com/questions/968949/how-to-prevent-events-from-being-bound-multiple-times

No comments: