I have two Javascript files, one is a react wrapper, the other is raw Javascript/html that is loaded in the react wrapper because the Javascript/html is older code. In the Javascript/html code I try to attach event listeners to each button in a <ul>
:
const previewItem = document.getElementsByClassName("previewItem");
for (let i = 0; i < previewItem.length; i += 1) {
previewItem[i].addEventListener('click', function(e) {
var event = new Event('previewItem');
previewItem[i].dispatchEvent(event);
});
}
And then in the react wrapper I handle the event like this:
const handlePreviewItem = e => {
this.showCompilationModal(
e.target.getAttribute('data-previewId'),
);
};
const previewItem = document.getElementsByClassName('previewItem');
for (let i = 0; i < previewItem.length; i += 1) {
previewItem[i].addEventListener('previewItem', handlePreviewItem);
}
The problem occurs because onload the dom might look something like this:
<ul>
<li><button data-previewId="1"></button></li>
<li><button data-previewId="2"></button></li>
<li><button data-previewId="3"></button></li>
</ul>
<ul>
<li><button data-previewId="4"></button></li>
</ul>
and after dragging from one list to another it could look like this:
<ul>
<li><button data-previewId="1"></button></li>
<li><button data-previewId="2"></button></li>
</ul>
<ul>
<li><button data-previewId="3"></button></li>
<li><button data-previewId="4"></button></li>
</ul>
After dragging from the top list to the bottom list and pressing the button with data-previewId="3"
, the e.target
in showCompilationModal
is actually the button after it in the dom which is data-previewId="4"
and it causes a bug. I can't figure out why or how this happens.