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

3

I have a modal of bootstrap that I use to register / login cadastroModal , but at the end of the request, I am reusing it to request the login and for this I added an event in onHiden , but I can not remove it after the call, so that it reopens the order completion screen.

If the user clicks to close the request and cancels the login screen, if he logs in normally he continues to fire 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);
    
asked by anonymous 08.07.2014 / 15:00

1 answer

4

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

The off API description is:

  

(original) The .off () method removes event handlers that were attached with .on ().
  (translated) The .off () method removes event occult 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 this:

$('#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 use 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 indicate the same function (and anonymous functions can not be referenced), what happens is that it removes the all event handlers for that element.

    
08.07.2014 / 15:05