Skip to content
Advertisement

Javascript/JQuery Callback confusion

I’ve a Modal which I show for confirmation:

<div class="modal" tabindex="-1" role="dialog" id="modal">
    <div class="modal-dialog" role="document">
        <div class="modal-content">
            <div class="modal-header">
             ... Body ...
            <div class="modal-footer">
                <button type="button" id="btnCancel" class="btn btn-default" data-dismiss="modal">Cancel</button>
                <button type="button" id="btnOk" class="btn btn-primary" data-dismiss="modal">Ok</button>
            </div>
        </div>
    </div>
</div>

Here is the code for showing the above Modal..

var M = {
 confirm: function(body, yes, no) {
    $('#btnCancel').on('click', function() {
       $('#btnCancel').off();
       $('#confirm-modal').modal('hide');
       if (no) {
            return no();
       }
    });
    $('#btnOk').on('click', function() {
      $('#btnOk').off(); 
      $('#modal').modal('hide');
      if (yes) {
         return yes();
      }
    });
  }
}

And here is how I am using it… (In any view for example)

M.confirm("Body", function(){
   // Function Body
})

Now, the problem is: If I call confirm, it shows the Modal. But if I click Cancel and than again call confirm and this time, I hit OK: the function (second param in the snippet above) is called twice. If I hit cancel 10 times, the function above is called 10 times.

Any idea why this is happening?

Thank You.

Advertisement

Answer

Every time you call confirm you add an event handler to each of btnCancel and btnOk.

However, you only remove the effect handler on one of those buttons when that button is clicked.

So if you call confirm, then click btnCancel, then call confirm you’ll have two event handlers on btnOK: One from the first call to confirm and once from the second.

When either button is clicked you need to remove both event handlers.

… or just add the event handlers when the document is loaded and don’t touch them thereafter.

User contributions licensed under: CC BY-SA
1 People found this is helpful
Advertisement