1

I was troubleshooting an issue I was having with some $(".foo").click(function(){...you get the point...}); events no longer working when I loaded content through .load(). I found something that got me through the issue here: jQuery, how to rebind html-elements after .load()

One of the comments there suggested delegation was being used incorrectly, and mentioned the "OP concept of delegation".

I'd like to understand the problem with delegation a little better instead of just plowing through the fix and moving on.

Can someone explain or point to reference articles that explain the concepts of delegation in javascript and what the "OP concept of delegation is"? Google wasn't very helpful.

EDIT: OP as "Original Poster" totally makes sense after you guys pointed that out, hard to see how I missed that now. So with that out of the way, still looking for a good reference for delegation in javascript.

Community
  • 1
  • 1
Erik Hanson
  • 155
  • 5
  • Well, "OP" in the comments in that post means `Original Post` or `Original Poster`, i.e "OP concept" is rather user2108590's concept, or the concept used in the original post. – Teemu Jul 17 '14 at 15:28
  • Possible duplicate of: http://stackoverflow.com/questions/1687296/what-is-dom-event-delegation. Also, check out this blog post: http://davidwalsh.name/event-delegate – Greg Burghardt Jul 17 '14 at 16:31

1 Answers1

0

I think the comment was implying that the Original Poster (OP) was maybe not using the jQuery delegated event binding properly. Hard to tell since the Original Post doesn't have any examples.

The solution in that post, which works, is to rebind all the events after the ajax load completes.

But, another solution is to use the jQuery on event binding to bind elements to a permanent element, higher in the DOM tree, so that the events don't have to be rebound on every ajax load.

$(document).ready(function() {

    $("#containerDiv").on('click', 'button.loadedFromAjax', function() {
       ...handle the click event of a button that is loaded via ajax...
    });

    $("#someButton").on("click", function() { 
        $("#elementToReload").load("page-to-load.html", function() {
             ...no need to bind events here since they are bound already...
        });
    });
});

Depending on usage, this can have memory and performance gains over rebinding every load.

This jsfiddle shows an example of replacing the html of an element but not having to rebind each time.

Geoff
  • 9,290
  • 7
  • 35
  • 48
  • Is there a way to rebind a large number of functions easily or is it a better practice to use .on() for binding events instead of .click()? – Erik Hanson Jul 17 '14 at 16:30
  • .on() has the advantage of a single place to define the binding once. http://learn.jquery.com/events/event-delegation/ "It allows us to attach a single event listener for elements that exist now or in the future." – Geoff Jul 17 '14 at 16:56