Quantcast
Channel: Active questions tagged html - Stack Overflow
Viewing all articles
Browse latest Browse all 73992

The Delete function works once, then unmounts from the rest of the elements [JavaScript Modules]

$
0
0

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.


Viewing all articles
Browse latest Browse all 73992

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>