0

I'm pretty new to Javascript and am writing a Chrome extension which is offsetting the "click" function call in a list of emails on an emailing website. My problem is that the functions that I'm offsetting are being passed by reference, which is causing them to eventually all point to a single click event.

My code:

//Offsets the email links
for (var i = emails.length - 1;  i >= amountToRemove; i--) {
   var a = emails[i];
   var b = emails[i - amountToRemove];

   a.addEventListener('click', (x) => {b.click(); x.stopPropagation(); return false;})      
}

And a little elaboration of the problem: ie. say amountToRemove is 2 and i = 10; the first two "shifts" of click() events go well, but in the 3rd shift, the click() function for the 9th (last) and 7th objects in the array point to the same function, which is not what was intended. I've tried making a "deep copy" of the function using

JSON.parse(JSON.stringify(object)) 

as well as other methods recommended by the internet to no avail.

My question is, is there a way of making a "deep" copy of the .click() functions so that they don't point to the same object and cause each click event to eventually point to the same single click event?

Sarah Sukardi
  • 45
  • 1
  • 8

1 Answers1

0

It seems like your problem is not about needing a "deep" copy of functions. Instead, I think your issue is that when you click on the 9th email, it triggers click on the 7th email, which then triggers click on the 5th email. A slightly hacky way to do what you want would be:

//Offsets the email links
var interceptingClick = false;
for (var i = emails.length - 1;  i >= amountToRemove; i--) {
   var a = emails[i];
   var b = emails[i - amountToRemove];

   a.addEventListener('click', (x) => {
       if (interceptingClick)
            return;
       interceptingClick = true;
       b.click(); 
       interceptingClick = false;
       x.stopPropagation(); 
       return false;
   });      
}

But the behavior you're trying to achieve seems a bit strange. Maybe you could tell us why you want to do that in case there's something else you could do that's easier and more robust.

arghbleargh
  • 3,090
  • 21
  • 13