简体   繁体   中英

How to stop function being called multiple times

I can't figure out why my code is triggering multiple calls of a function. I'm creating a calendar app and each time I delete an event, it increments the number of times the function gets called. It must be something to do with the for loop which I've tried to resolve using 'break' but doesn't work.

When the user opens a day in the calendar, it displays the events. I have an event listener to trigger a modal of "Are you sure you want to delete event?".

// Delete event
delEvent = document.getElementsByClassName('eventEntry');
for (var e = 0; e < delEvent.length; e++) {
    delEvent[e].addEventListener('click', delete_event,false);
    break;
}
// Opens model to prompt event delete
function delete_event(d){
    id = d.currentTarget.id;
    $('#modal-delete').modal('open');
    delModalBtn = document.getElementsByClassName('delTrue');
    for (var i = 0; i < delModalBtn.length; i++) {
        delModalBtn[i].addEventListener('click', event_del_true,false);
        break;
    }
}

When the user confirms they want to delete the event, event_del_true function is called (code below). This technically works but the Toast popup component from MaterializeCSS displays multiple times.

For example:

  • Delete 1 event = event is deleted and popup is displayed.

  • Delete a 2nd event = the event is deleted but the popup displays twice, and so the cycle begins

     function event_del_true(){ $.ajax({ type: "POST", url: "php/delete-event.php", data: {id: id} }).done(function() { M.toast({ html: 'Event deleted', classes: 'rounded', displayLength: 2000, inDuration: 375, outDuration: 300 }); });

Any help would greatly be appreciated, Kind Regards.

Why do you need to add a loop here if you break the loop in the first iteration?

for (var i = 0; i < delModalBtn.length; i++) {
    delModalBtn[i].addEventListener('click', event_del_true,false);
    break;
}

Plus, every time you trigger the function, you are adding another event listener to the button, so the effect event_del_true will be added on top of each other every time you call delete_event

a simple fix would be moving this line out of the function

// Opens model to prompt event delete
function delete_event(d){
    id = d.currentTarget.id;
    $('#modal-delete').modal('open');
}

// add the event to every button with the class ONCE only
delModalBtn = document.getElementsByClassName('delTrue');
for (var i = 0; i < delModalBtn.length; i++) {
    delModalBtn[i].addEventListener('click', event_del_true,false);
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM