2

The problem I'm currently wrestling with is this. Haven't realised what the issue was but i have the following code

j.prototype.deleteFile = function()
{

  $('.deleteFile').on('click', function()
  {

    if(confirm('Are you sure you want to delete this file?'))
    {

      //delete the file

    }

  })

}

The purpose of this is to delete files on button click and confirmation of deletion. Since file icons are added upon uploading (appended afterwards) and this is called upon page load (since upon page load there might already be files for deletion) i need to refetch the HTML elements to have an up to date list as i understand. This creates multiple instances of the function as it is called multiple times (for each upload) and thus when trying to delete a file:

  • After first upload asks for confirmation once
  • After second upload, second upload asks for confirmation once, first one twice.

The pattern is to add additional one for the ones existing before. I assume it is because deleteFile has multiple instances and each of them triggers upon click.

I have been looking for a way to clear the old instances or maybe add/include new elements to that old instance but to now avail.

Is there a method for achieving my goal that I'm overlooking maybe?

Matthew Herbst
  • 29,477
  • 23
  • 85
  • 128
NulisDefo
  • 325
  • 2
  • 7
  • 19
  • 1
    This is a use case for *event delegation*, see the linked question's answers: Use [jQuery's support for it](http://api.jquery.com/on/#on-events-selector-data-handler) by hooking the click on `document` or whatever common ancestor these `.deleteFile` elements have, and then tell jQuery only to call your handler when the event passes through `.deleteFile` element: `$(document).on("click", ".deleteFile", function() { /*...*/});` That way, there's no need to rediscover the elements when you add them, since the handler is actually on `document`, not the elements themselves. – T.J. Crowder Dec 11 '18 at 11:21
  • @T.J.Crowder Works like a charm. Never really investigated other options of the `on()` function. Thanks for the tip. But the issue with this is though that when new files are upload new files, the delete button becomes immediately available (which my flawed method prevented) and if the user was to click it mid-upload, it would try to delete a non-existing file. I could of course add the icons AFTER upload, but I was wondering if You would have any other bright suggestions on this case? – NulisDefo Dec 11 '18 at 12:02
  • 1
    I think that's probably the way to go, perhaps have a loading indicator where the delete button would be. Alternately, give it a `disabled` (or similar) class which shows it in a disabled state, and make the delegation selector you pass `on` `".deleteFile:not(.disabled)"`... – T.J. Crowder Dec 11 '18 at 12:11

0 Answers0