Skip to content Skip to sidebar Skip to footer

Jquery Bind() Unbind() And On() And Off()

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

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().

Post a Comment for "Jquery Bind() Unbind() And On() And Off()"