Morta 1 Morta 1 - 4 months ago 24
Javascript Question

addEventListener firing twice

I'm creating a simple phonebook, that adds person name, last name and phone into a div and into the DOM, with option to delete this div with click event.
I have a class called Phonebook which contain these 2 functions:

//add an event button to all divs inside the DOM
this.deleteBtnEvent = function(){
var _this = this;
//get all the divs that currently on the DOM
var deleteBtn = document.getElementsByClassName('delete');
for (var i = 0; i < deleteBtn.length; i++) {
deleteBtn[i].addEventListener('click', function(e){
_this.removeContact(e.target.parentElement.attributes.index.value);
});
}
};

//remove the div from the array and from the DOM
this.removeContact = function(index){
var contactsHolder = document.getElementById('contacts');
var contact = document.getElementsByClassName('contact');
this._contacts.splice(index, 1);

contactsHolder.removeChild(contact[index]);

//update localstorage
var stringArr = JSON.stringify(this._contacts);
localStorage.setItem('data', stringArr);

console.log('current: ');
console.log(this._contacts);
};


for some reason the addEventListener is firing twice.
first time that the addEventListener is called, the function delete the div from the DOM and the array, the second time the listener is fired, i'm getting an error because the div with the same ID doesn't exist, because its already deleted.
I'm wondering if there's a way to solve this issue.

Answer

In addContact(), you call this.deleteBtnEvent(), presumably to bind deletion to the delete button that was just added. In deleteBtnEvent(), however, you're binding an event listener to all delete buttons on the page. This means the following will happen:

  1. Add a contact. A new contact will show up with a delete button that has a listener.
  2. Add a second contact. A new contact will show up with a delete button that has a listener, and a second listener will be added to the first button.
  3. Add a third contact. A new contact will show up with a delete button that has a listener, and a third listener will be added to the first button, and a second listener will be added to the second button.
  4. etc....

So, in deleteBtnEvent(), don't add (duplicate) listeners to all delete buttons. Instead, only add a listener to the delete button that was just created via addContact().

Comments