Jquery accumulating events

1

I have a problem in a listing, it is the following, I have a table, for each line has a link to be able to edit the line, with this, clicking this link opens a bootstrap modal with all its content coming via Ajax, and it's all right so far. And when I close the modal I call an event of it to be able to update the table row.

My problem is that you are accumulating calls for this line update, for example: I have the first line, I click the edit button, open the modal, and when I close this mode it updates me the data of the clicked line; so when I click on another link to edit (or even the same), opens the modal and hence when I close this mode it updates me the data of the clicked line, but looking at the console I see that it makes the first and the second call of the lines to be updated, what can be accumulating these calls that only happens when I close the modal?

This is an idea of the code, which happens in this case is that every time you open the modal, when it closes will accumulate the alert

$('a.edit_row_dt').on('click', function(e) {
    e.preventDefault();

    var item_id = $(this).data('id');
    var row = $(this).closest('tr');

    $('#edit').load('edit.php', {"id" : item_id}, function(){
            $('#edit').modal();

            $('#edit').on('hidden.bs.modal', function(event) {
                event.preventDefault();
                alert(item_id); // aqui 
                $('.modal-dialog').remove();
            });
        }
    );
});
    
asked by anonymous 18.04.2016 / 21:47

2 answers

2

Before adding a handler to the "hidden.bs.modal" event, try removing the previous handler using the off of jQuery:

// Essa linha
$('#edit').off('hidden.bs.modal');

$('#edit').on('hidden.bs.modal', function(event) {
      event.preventDefault();
      alert(item_id); // aqui 
      $('.modal-dialog').remove();
 });
    
18.04.2016 / 22:09
2

Use .one() instead of .on() when closing modal, when you use .on() it runs again with every click.

$('#edit').one('hidden.bs.modal', function(event) {
    event.preventDefault();
    alert(item_id); // aqui 
    $('.modal-dialog').remove();
});

JSFiddle

    
18.04.2016 / 22:11