2

I have a JavaScript class like so:

export class btnNumbers {

    constructor(index){
        this.index=index;
        this.btn = document.createElement(`div`);
        
        this.btn.classList.add('btn__normalState');
        this.btn.innerText = index;
        this.btn.addEventListener('click', this.showIndex )
        
        const btnContainer = document.getElementById('btnContainer');
        btnContainer.appendChild(this.btn);
    }

    showIndex(){
        console.log(this.index)
    }

and I am using this class in another js file like so:

for ( let i=1; i<=500 ;i++){
    var btn = new btnNumbers(i);}

so this creates 500 of theses elements that are clickable, and they should return the index, but it does not, it returns undefined instead.

I can't understand why...

Heretic Monkey
  • 11,687
  • 7
  • 53
  • 122
julBayonna
  • 409
  • 7
  • 19

1 Answers1

1

You need to bind the this value of the event handler function or use an arrow function; otherwise, the this value will be set to the HTML element on which the event listener is attached.

this.btn.addEventListener('click', this.showIndex.bind(this));
// or
this.btn.addEventListener('click', ()=>this.showIndex());

class btnNumbers {
  constructor(index) {
    this.index = index;
    this.btn = document.createElement(`div`);
    this.btn.classList.add('btn__normalState');
    this.btn.innerText = index;
    this.btn.addEventListener('click', this.showIndex.bind(this))
    const btnContainer = document.getElementById('btnContainer');
    btnContainer.appendChild(this.btn);
  }

  showIndex() {
    console.log(this.index)
  }
}
for (let i = 1; i <= 500; i++) {
  var btn = new btnNumbers(i);
}
<div id="btnContainer">
</div>
Unmitigated
  • 76,500
  • 11
  • 62
  • 80