I have the following function to open the popup.
When the confirm button is clicked, it will process the request
function OpenConfirmPopup(title, msg, func) {
var mymodal = $('#confirmModal');
mymodal.find('.modal-title').text(title);
mymodal.find('.modal-body').text(msg);
mymodal.modal('show');
$('.btn-confirm').click(function () {
var args = new Array();
for (var i = 1; i < arguments.length; i++)
args.push(arguments[i]);
window[func].apply(this, args);
});
}
And here is the caller
function ConfirmAttendance() {
OpenConfirmPopup("Attendance", "Are you sure you want to confirm the attendance?", "ConfirmAndCloseSession");
}
And this is the button
<button class="btn btn-primary btn-confirm" data-dismiss="modal">Ok</button>
<button class="btn btn-default" data-dismiss="modal">Cancel</button>
If I call ConfirmAttendance
, then cancel, then call again and click ok, it seems the request is done twice. What am I doing wrong here?
2
Answers
I made a workaround by unbinding and rebinding the event, using
off
followed byon
:The issue is because you attach a new
click
event handler to the button every time the modal is shown. Move that logic outside of the function.The only issue there is that you will need to pass the
func
variable through theOpenConfirmPopup()
function to the click handler. This can be done using adata()
attribute on the element:I’d also question the purpose of creating the
args
array fromarguments
. The two arrays will be identical, so just provide arguments direcly:If you’re doing this in order to clone the array use
slice()
:Or spread syntax (if the browsers you’re targeting support ES6):