I know that for Javascript events best practice is always remove events that you are no longer use. But what about the event that is attached to a HTML DOM element that I am going to remove, should I remove the event first then remove the DOM element or I can just remove DOM element straight away and not worry about the event that is attached to it?
Example:
const mainContainerEl = document.querySelector('.main-container');
const addBtnEl = document.querySelector('.add-btn');
const removeBtnEl = document.querySelector('.remove-btn');
const outputTextContent = (e) => {
console.log(e.currentTarget.textContent);
}
addBtnEl.addEventListener('click',()=>{
/* Click to create 5 span DOM elements and add event to each
one then append each one of them to mainContainerEl */
for(let i = 1; i <= 5; i++){
const newSpanEl = document.createElement('span');
newSpanEl.textContent = i;
newSpanEl.addEventListener('click', outputTextContent);
mainContainerEl.append(newSpanEl);
};
});
/* Should I do something like this? */
removeBtnEl.addEventListener('click',()=>{
if(mainContainerEl.firstChild){
const mainContainerElChildren = [...mainContainerEl.children];
mainContainerElChildren.forEach((childEl)=>{
/* Remove event first*/
childEl.removeEventListener('click',outputTextContent);
/* After the event is removed, remove the element */
childEl.remove();
});
}
});
If I don't remove the event first and just remove the DOM element straight away, is the event going to get removed after the DOM element is removed(will the garbage collector collects both of the event and the DOM element and released them from the memory)?
question from:
https://stackoverflow.com/questions/65649861/remove-event-before-remove-dom-element-everytime 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…