How to remove events associated with elements via ". on('acao'"

Asked

Viewed 438 times

3

I have a modal from bootstrap I use to register/login cadastroModal, but at the end of the order, I’m repurposing it to request the login and for that I added an event on onHiden, but I can’t remove it after the call, so it opens the order checkout screen again.

If the user clicks to close the order and cancels the login screen, if he logs in normally he continues to trigger the event

Event association

self.closeOrder = function () {
    if (!self.hasLoggedUser()) {
        $('#carrinhoModal').modal('hide');
        $('#cadastroModal').modal('show');
        $('#cadastroModal').on('hidden.bs.modal', function (e) {
            // retorna ao comportamento anterior, só precisávamos agora
            $('#cadastroModal').on('hidden.bs.modal', function (e) {});
            if (self.hasLoggedUser()) {
                $('#pedidoModal').modal('show');                    
            }
        })
    } else {
        $('#pedidoModal').modal('show');    
    }
}

Attempts:

$('#cadastroModal').on('hidden.bs.modal', null);

$('#cadastroModal').on('hidden.bs.modal', undefined);
  • 2

    .off http://api.jquery.com/off/

1 answer

4


For each .on() there is a .off().

To description of the off API is:

(original) The . off() method removes Event handlers that Were Attached with . on().
(translated) The . off() method removes event settings created with . on().

It is important to refer to the same function at the time of .off(). I suggest changing your code. Instead of having so:

$('#cadastroModal').on('hidden.bs.modal', function (e) {
    // retorna ao comportamento anterior, só precisávamos agora
    $('#cadastroModal').on('hidden.bs.modal', function (e) {});
    if (self.hasLoggedUser()) {
        $('#pedidoModal').modal('show');                    
    }
})

should wear like this:

function handler(e) {
    // retorna ao comportamento anterior, só precisávamos agora
    $('#cadastroModal').on('hidden.bs.modal', function (e) {});
    if (self.hasLoggedUser()) {
        $('#pedidoModal').modal('show');                    
    }
}

$('#cadastroModal').on('hidden.bs.modal', handler);

and when you want to remove, use

$('#cadastroModal').off('hidden.bs.modal', handler);

If you do not specify the same function (and anonymous functions cannot refer to) what happens is that it removes all the Vent handlers for this element.

  • 1

    Thank you! I searched for the wrong words

  • 1

    @Caputo if my answer solved your question can click to accept the answer.

  • Sorry for the delay in accepting, I ended up returning to the site only today.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.