jQuery bind() unbind() and on() and off()

10,528

Solution 1

Unbinding only to bind again for performance reasons is probably bug-prone and makes things overly complicated in most cases.

Instead of binding event listeners on many specific DOM elements, you could take a more "birds eye" approach and bind just a few listeners near the top of the DOM tree, and then when the event is triggered check what was actually clicked.

That way you won't spend CPU on binding/unbinding lots of event listeners, but instead take a small CPU hit when an event is processed (which is usually not noticeable).

This is covered in detail here: event delegation vs direct binding when adding complex elements to a page

Solution 2

If you try to bind and unbind you are creating race conditions for the garbage collector to actually come in and clean up your code. It is best to bind once and not have to bind again. If your client side is expected to run for long periods of time (weeks, months) then you should look into memory management and memory leaks as more of a concern for performance.

Binding-unbinding (if not done correctly) may produce memory leaks which are hard to find. If you are using webkit, take heap snapshots of your performance with unbinding versus binding once and then you can make the best decision.

Here's a link:

http://addyosmani.com/blog/taming-the-unicorn-easing-javascript-memory-profiling-in-devtools/

Solution 3

One solution to avoid having to worry about this, especially if you deal with constantly changing elements or large quantities, is to register your event with the body and then specify a selector argument.

Like this:

$("body").on("click", ".my-actual-element", function(aEvent) {
   // Event handler code goes here.
});

See more here $.on().

Share:
10,528
mr_app
Author by

mr_app

Updated on June 25, 2022

Comments

  • mr_app
    mr_app almost 2 years

    Im working on a small adminarea for a webpage.

    Does it make sense to unbind events for increasing performance(client)? Or does it cost more performance to unbind events and binding it 30Seconds later again?

    My questions: Is the idea behind bind()-unbind() or on().off() just increasing clientbased performance or should i use it for other scenarios? This question comes because my javascript code is growing and growing (about 30%) because of unbinding events. And i think, that some things may not work, when user interacts not, as i want...

    .

    EDIT: The most times im binding/unbinding keypress events, because i need the arrow keys for diff. scenarios.