UPDATE: Here's a shorter and a simpler snippet to demonstrate my problem. Try to click on the first button and its corresponding event listener does not work. Only the second one.
var a = {};
a.b = 0;
a.alert = () => {
a.b++;
document.getElementById('X').innerHTML += '<button id="_'+a.b+'">Button #'+a.b+'</button>';
document.getElementById('_'+a.b).addEventListener('click',(e)=>{
var p = document.getElementById('_'+a.b);
p.parentElement.removeChild(p);
});
}
a.alert();
a.alert();
<!DOCTYPE html>
<html lang="en">
<body>
<span id="X"></span>
</body>
</html>
UPDATE: It seems that I really lose the event. I checked DevTools and the created elements prior to that lose the click event when I execute the function again.
I would like to ask for some help with trying to tame event listeners. It seems that if I try to call the function multiple times, only the last function seems to work, which is a problem since I would like to have the ability to show multiple alerts. Here's what I'm trying to do.
Is there something that I'm missing here? Or is this a problem with using objects to contain functions?
var alertify = {}
alertify.depth = [];
alertify.alert = (title, text, callback = () => {}) => {
var uniq = 'uniqalert_'+uniqid();
alertify.depth.push(uniq);
var content =
'<form onsubmit="return false" class="dialog" id="'+uniq+'">\
<div class="box">\
<div class="box_title">\
<div class="box_title_content">'+title+'</div>\
<img id="i'+uniq+'" src="'+operator.config.ximage+'">\
</div>\
<div class="box_content">'+text+'</div>\
<div class="box_button">\
<button class="yes" id="j'+uniq+'">OK</button>\
</div>\
</div>\
</form>';
selector('alertcontainer').innerHTML += content;
var f = selector(uniq);
selector('i'+uniq).addEventListener('click',()=>{
callback();
f.parentNode.removeChild(f);
});
selector('j'+uniq).addEventListener('click',()=>{
callback();
f.parentNode.removeChild(f);
});
}
Note: I am not affiliated to the alertify/js team. I just used that var name as I'm accustomed to using it before.