Question

I have this piece of code:

$('.self_delete').on('ajaxSuccess', function(event, xhr, settings) {
    json = jQuery.parseJSON(xhr.responseText);
    if ($(this).attr('href') == json.delete_url ) {
        alert('going to delete');
        $(this).closest($(this).data('parent-selector')).remove();
    } else {
      alert('not this one!');
    }
});

which works perfectly for elements which are already on the page. But when I dynamically add new ones and click on the .self_delete element, it does not trigger the ajaxSuccess (but the link works).

If there are already a few items in the page, I add another one and then click on the newest one to trigger the event, the alert "not this one!" will be triggered for the existing elements but not the new one.

Any ideas? ----EDIT----- I use the delegate like this:

$('#lists').on('ajaxSuccess', '.self_delete', function(event, xhr, settings) {
    json = jQuery.parseJSON(xhr.responseText);
    if ($(this).attr('href') == json.delete_url ) {
        alert('going to delete');
        $(this).closest($(this).data('parent-selector')).remove();
    } else {
      alert('not this one!');
    }
});

and now the event never fires, even when the page is reloaded. But the selector is good because doing $('#lists .self_delete') does return an array of the a.self_delete ! (going to sleep, hope someone has a suggestion when I wake up! thx!)

---EDIT 2----- if I add this:

$('#lists').on('click', '.self_delete', function(event) {
    alert('going to delete from click');
});

the alert does fire. In all cases. So basically, it seems like .on() can't register the ajaxSuccess event! I tried to google on this, but searching for anything related to .on() is like missing impossible, it is such a common word :-S

No correct solution

OTHER TIPS

$('.self_delete'). <- this part is being run once - the first time the document loads - and attaches your handing function to all the elements with the class self_delete.

You need to use delegation. Attach the handler to a containing object, (in the example below, .container), and evaluate for .self_delete each time the handler is called.

$('.container').on('ajaxSuccess', '.self_delete', function(event, xhr, settings) ...

Read more about .on()

You will have to reapply the bind once dynamic contents are created.

after talking to a few people on the chat room, it seems like ajaxSuccess has to be attached to an element and cant bubble up. So I fixed my problem by attaching the .on() to the parent of the .self_delete items and the use the $.ajax from there which gave me access to the ajaxSuccess as expected.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top