Javascript callback issues

0

I have a div modal bootstrap that stays in 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, a javascript function passed by parameter is executed.

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

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

Example calling 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 the user clicks Cancel, and then clicks again the button that runs salvarPlaca , and the second time to confirm, the efetivarAlteracaoPlaca function is running twice.

    
asked by anonymous 16.09.2016 / 22:34

1 answer

2

You are associating a new event with the btnConfirmarAlteracao element every time you call the confirmarAlteracao function. Either you apply the unbind of the previously registered function, or you adopt 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 pass you a solution using Promises .

    
16.09.2016 / 23:03