Unbind/bind vs. delegate in jQuery: Which is the best solution?

873 Views Asked by At

I have jQuery code that handles unbinding and binding event handlers to elements that are dynamically added to the page. The code has a wrapper function that unbinds existing handlers from elements with a given id prefix, and then binds the event handlers so that any existing elements have the handler and any newly added elements of the same id prefix get it as well. Obviously this does extra unbinding/binding on elements with the id prefix that already exist when a new element is added. The unbind is done to prevent existing elements getting multiple handlers of the same type assigned to them.

Since originally writing this code, I have learned about the jQuery delegate function that essential seems to do exactly what I have done above.

Would the delegate function do what I have done significantly better, such that it would be worth my time to rewrite my current working code to take advantage of it? By better I mean performance, memory use, or some other measure.

1

There are 1 best solutions below

3
On BEST ANSWER

When you use .delegate(), you are expected to choose an ancestor element that will be the listener for events on designated descendents. Which is great because right from the beginning you are binding a listener that should be more or less "permanent" on your page, regardless of how many valid targets are added or removed from its descendent tree.

This is certainly better than .click for dynamic pages, and is better than using a series of .bind and .unbind on elements as they get added or removed.

However, it might be equal to using .bind() in a way that chooses an ancestor element that listens for clicks on designated descendents. I'm not familiar enough with .bind() to say for sure about performance benefits.

--

As an aside not specifically related to your question, it IS a better-performing function than .live(), so if you are ever tempted to use .live() I would strongly recommend .delegate() as a better option.