I've been practicing using JavaScript modules and I need somebody to help me understand why the delete function is not working properly. I'm assuming after I add a person, something happens in binding?
(function() {
let people = {
people: ['will', 'john'],
init() {
this.cacheDOM();
this.render();
this.bindingEvents();
},
cacheDOM() {
this.$inputVal = document.getElementById('input');
this.$target = document.getElementById('template');
this.$button = document.getElementById('btn');
this.$DOMLis = document.getElementsByClassName('elems');
},
bindingEvents() {
this.$button.addEventListener('click', this.addName.bind(this));
//Adding event listener "delete" to the lis
this.$keys = Object.keys(this.$DOMLis);
this.$keys.map(val => {
this.$DOMLis[val].addEventListener('click', this.remove.bind(this));
});
},
render() {
this.$target.innerHTML =
'<ul>' +
this.people
.map((val, i) => {
return `<li key=${i} class='elems' name='${val}'>${val}</li>`;
})
.join('') +
'</ul>';
},
addName() {
this.people.push(this.$inputVal.value);
this.render();
},
remove(e) {
let index = parseInt(e.target.getAttribute('key'));
this.people.splice(index, 1);
this.render();
},
};
people.init();
})();
And this is the HTML
<div id="root">
<div id="template"></div>
<input id="input" type="text" />
<button id="btn">un</button>
</div>
<script type="text/javascript" src="./script.js"></script>
The addPerson function seems to work fine with everything else, but the delete function is not.
Your bindingEvents()
function adds a click event listener to each of the elems
created by your render()
function. The next time render()
is called (after an add or remove), all elems
are removed and recreated, but the listeners are not re-added.
You will need to either change the way that render()
is working, or re-add the click event listeners to each of the elems
, each time you render.