3

If I assign a function to a variable foo, is there a way to select all elements that do not have a binding to foo given that they are assigned via a structure like $('.elementsWithClass').click(foo)?

My motivation here is we have ajax requests replacing parts of the DOM, and I need an easy way to rebind event handlers that is not based on .live/.on as we are controlling event bubbling in some parts of the application.

Joshua Enfield
  • 17,642
  • 10
  • 51
  • 98
  • 1
    duplicate of [test if event handler is bound to an element in jquery](http://stackoverflow.com/questions/1236067/test-if-event-handler-is-bound-to-an-element-in-jquery) – MrOBrian Aug 16 '12 at 18:36

1 Answers1

3

Regarding the motivation for doing this, since they are assigned with $(".elementsWithClass").click(foo), you should just reselect them after the DOM has been updated.

$("#container").load("/new/content.html", function() {
    $(this).find(".elementSWithClass").click(foo);
});

Since they need to be rebound, that must mean they've been replaced, which means it won't do any good to select them based on if they have a handler.

gray state is coming
  • 2,107
  • 11
  • 20
  • I would suggest unbinding the click even before binding it again, as there could be elements sill on the page that were previously bound. Or prevent bubbling inside of foo. Example: http://jsfiddle.net/gromer/QAyB5/. If you uncomment the unbind line, you'll only get a single line written to the console (single function call) per click. When it is commented, you'll get a line for each click binding. – Gromer Aug 16 '12 at 18:48
  • @Gromer: It depends on how the DOM is being replaced. Given my example, everything inside `#container` is being replaced, so there's no need to manually unbind. The binding is only happening inside `#container`. If we unbind from `document`, we may be unbinding some that shouldn't be. – gray state is coming Aug 16 '12 at 18:50
  • Ahh, good point, since the container content is getting *replaced*. Good call, sir! – Gromer Aug 16 '12 at 18:51
  • @Gromer: Yes, but your point is very valid if the new content is being appended along side other elements that are already bound. – gray state is coming Aug 16 '12 at 18:55