Yi Wang
Yi Wang

Reputation: 1015

jQuery how to bind event to element which is deleted and added again

I am using jQuery and a modal library named jQuery.Modal. I have a customize function to show this modal in order to fit the UI design:

show: function (option) {
    var view = new Modal.View();
    sdhapp.modalRegion.show(view);
    $(".sdh-ui.modal-header").html(option.title);
    $(".sdh-ui.modal-body").empty();
    if (option.image) {
       if (option.image === 'error') {
          $(".sdh-ui.modal-body").append(
                  '<div class="image-box" style="background-image: url(images/error-icon.png)"></div>');
       }
    }
    if (option.confirmButton === true) {
       $(".sdh-ui.modal-footer").html(
               '<button type="button" id="modal-confirm-button">Confirm</button><button type="button" id="modal-cancel-button">Cancel</button>');
    }
     $(".sdh-ui.modal-body").append(option.body);
    $('#error-modal-form').modal({
       showClose: false
    });
    bindModalEvents(option);
}

Where view is Marionette view that renders the modal body.

I am binding the click events:

  $('#modal-cancel-button').on('click', function () {
     unbindModalEvents();
     $.modal.close();
     if (option.cancel)
        option.cancel.call();
  });
  $('#modal-confirm-button').on('click', function () {
     unbindModalEvents();
     $.modal.close();
     if (option.confirm)
        option.confirm.call();
  });
  $('#modal-ok-button').on('click', function () {
     unbindModalEvents();
     $.modal.close();
     if (option.ok)
        option.ok.call();
  });

and unbind it: var unbindModalEvents = function(){ console.log('called'); $('#modal-cancel-button').unbind('click'); $('#modal-confirm-button').unbind('click'); $('#modal-ok-button').unbind('click'); };

the problem is that the click event ( the close function ) is only triggered once. If I the modal is shown for a second time, the click events is not triggered

I tried to remove the element, using "bind" instead of "on" but nothing works

Any advice?

Upvotes: 0

Views: 411

Answers (1)

Will Reese
Will Reese

Reputation: 2841

When you close the modal, it's deleted from the DOM. That means that any event handlers bound to will also disappear. Try this:

$('body').on('click', '#modal-cancel-button', function () {
  unbindModalEvents();
  $.modal.close();
  if (option.cancel)
     option.cancel.call();
});
$('body').on('click', '#modal-confirm-button', function () {
  unbindModalEvents();
  $.modal.close();
  if (option.confirm)
     option.confirm.call();
});
$('body').on('click', '#modal-ok-button', function () {
  unbindModalEvents();
  $.modal.close();
  if (option.ok)
    option.ok.call();
});

This binds the handler to the body, which then watches for events that originate from modals. You can add and create as many as you'd like and the handler won't get deleted.

Upvotes: 1

Related Questions