2

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.

Carvell Fenton
  • 2,341
  • 6
  • 23
  • 30

1 Answers1

1

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.

Greg Pettit
  • 10,749
  • 5
  • 53
  • 72
  • I just read that about .live vs .delegate before posting the question :) I am not taking advantage of anything you describe in your third paragraph. I am doing the unbind/bind on the specific element collections themselves, selected as $('[id^="idprefix"]')... So I am not using an ancestor element at all for listening. I am guessing that would mean my multiple unbinds/binds for elements that already had the handler would be a negative performance hit over .delegate? – Carvell Fenton Oct 06 '11 at 18:52
  • Yup, the way you're using bind/unbind will not perform as well as .delegate in that case. Make the switch; you know you want to... .delegate() is so much more elegant anyhow. ;-) – Greg Pettit Oct 07 '11 at 02:05
  • :) Yeah, you got me! Refactoring here I come. Thanks for your help. – Carvell Fenton Oct 07 '11 at 11:38