Problems with Javascript callback

Asked

Viewed 113 times

0

I have a div bootstrap modal that sits on the "masterpage" _Layout.csthml.

<div id="ModalAlteracao" class="modal fade">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header">
                <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">&times;</span></button>
                <h4 id="TituloModalAlteracao" class="modal-title">Atenção</h4>
            </div>
            <div class="modal-body">
                <p>
                    Houve alteração de dados nesta tela, as demais informações das telas seguintes serão apagadas.
                </p>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-danger" data-dismiss="modal">Cancelar</button>
                <button id="btnConfirmarAlteracao" type="button" class="btn btn-primary">Salvar</button>
            </div>
        </div><!-- /.modal-content -->
    </div><!-- /.modal-dialog -->
</div>

I created a function that is called in several different Views, to open this modal, and when clicking the Save button, run a javascript function passed by parameter.

function confirmarAlteracao(callback) {
        $("#btnConfirmarAlteracao").click(function () {
            callback();
            $('#ModalAlteracao').modal('hide');
        });

        $('#ModalAlteracao').modal('show');
 }

Call example of this function:

function salvarPlaca() {
    if (!houveAlteracaoPlaca()) {
        efetivarAlteracaoPlaca();
    }
    else {
        // exibe o dialog de confirmação, e passa a função de callback caso o usuário clique em "sim"
        confirmarAlteracao(efetivarAlteracaoPlaca);
    }

}

The problem is that if user click Cancel, and then click again on the button that runs salvarPlaca, and this second time confirm, the function efetivarAlteracaoPlaca is being executed twice.

1 answer

2


You are associating a new event with the element btnConfirmarAlteracao every time you call the function confirmarAlteracao. Or do you apply the unbind of the previously registered function, or adopts another strategy. Here is an example using closures to solve the problem:

var currentCallback = $.noop;

$("#btnConfirmarAlteracao").click(function () {
    currentCallback();
    $('#ModalAlteracao').modal('hide');
});

function confirmarAlteracao(callback) {
    currentCallback = callback;
    $('#ModalAlteracao').modal('show');
}

NOTE: I would prefer to use Promises in this scenario... as I’m leaving work now, when I get home I edit this answer to give you a solution using Promises.

  • Thanks.This solution worked out! If you are going to post the others, and it works out I accept the answer. But for now this met in a simple way!

Browser other questions tagged

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