-2

It's very easy to event-handle when dealing with items the document has from the get go:

$(document).ready(function() {
    $('.element-in-question').on("event", function (event) {
        //do what you need to do during the event
    });
});

My problem is how would I best deal with dynamic elements. For example, let's say I dynamically load notifications, some of which are friend requests during an AJAX request. Would I create the event-handler in the success callback, or would I do it somewhere else?

The way I would currently go about it:

$(document).ready(function() {
    $.ajax({
        url: '/friendships/requests',
        type: 'GET', 
        success: function(responseData) {
            //dynamically create your elements (with classes accepted and rejected)
            $('.accepted, .rejected').on("click", function(event) {
                //do what is needed in this event
            });
        }
   });
});

Is this the idiomatic way to go about it, or is there another way I probably should be going about it?

Brian Tompsett - 汤莱恩
  • 5,753
  • 72
  • 57
  • 129
David
  • 7,028
  • 10
  • 48
  • 95

3 Answers3

1

If you dynamically create an element, such as a 'button', that was not on the page before, handle it like this:

$(function() {

    (function() {
        $('body').append('<button id="newButton">Hello World!</button>');
    })();

    $('body').on('click','#newButton',function() {

        console.log($(this).html()); //"Hello World!"

    });


});
Josh Beam
  • 19,292
  • 3
  • 45
  • 68
1

use jquery's "on" merhod to bind event handler to parent element (which will not change) and pass a selector of the element you want to listen to:

$('.parent').on('event', '.child', handlerFunction);
Daiwei
  • 40,666
  • 3
  • 38
  • 48
-2

I think this is the (partly) right approach. You cannot and should not apply eventhandlers to objects that might or might not be available, even if possible.

If the situation would involve 10000 different eventhandlers, they should be only available when present in dom. When removed the eventhandler should be removed as well.

The way you do it is rudimentary but correct.

2 other thoughts. If you bind the listener in the ajax callback you might add to the "stack" of events, since they are not replaced. Not a good thing. If the ajax query will happend more than once, do not add it again, if not removed first.

Another aproach might be to just add them to all pages, if this is a small page/application and first check that the element exist. Like so:

if ($('#id').size() > 0) { 
// bind events for #id here
}
Björn3
  • 297
  • 1
  • 2
  • 8
  • First of all: You can! The "should not" might be correct in some cases but I think in most cases there are just items added to an already existing list where it is a lot cleaner to delegate the events from the beginning. – Marcel Gwerder Dec 29 '13 at 00:25
  • Regarding the should. I Agree. I was thinking in a big enviroment. A solution where there are a lot of handlers. Like the gmail interface. If you should choose one method to use all the time. The most correct might be to always only attach the currently used. Another problem with the samplecode above is that it might add to the stack to set the handlers in ajax call. Since it will not replace but add another handler. (i think) – Björn3 Dec 29 '13 at 09:37