6

I am new to ECMA classes.

In the following code, I have built a button class that is working fine. Now I am trying to call the prev_image() method from inside the click eventlistener. I know 'this' refers to the button instance but am not sure how to call a method from the Gallery class. Thanks for any help.

class Gallery{

    constructor(){
    }

    draw(){

        //build button
        prevbtn.draw();

        //button listener
        document.getElementById('prevbtn').addEventListener('click', function(){
            this.prev_image();   <--- this errors out
            console.log('pressed'); <--this works
        });

    }

    prev_image(){
        console.log('previous image!');
    }

}
barrylachapelle
  • 967
  • 4
  • 13
  • 34

3 Answers3

14
document.getElementById('prevbtn').addEventListener('click', ()=>{
            this.prev_image();   
            console.log('pressed');
        });

Use the arrow function here.Arrow function does not have its own this it uses this from the code that contains the Arrow Function

Saikat Hajra
  • 670
  • 3
  • 12
3

Try it by binding the context using .bind(this)

class Gallery {

  constructor() {}

  draw() {

    //build button
    //prevbtn.draw();

    //button listener
    document.getElementById('prevbtn').addEventListener('click', function() {
      this.prev_image();
      console.log('pressed');
    }.bind(this));

  }
  // prevbtn.draw(){
  //console.log('prev btn')
  //}

  prev_image() {
    console.log('previous image!');
  }

}

var x = new Gallery();
x.draw();
<button id='prevbtn'>Click</button>
brk
  • 48,835
  • 10
  • 56
  • 78
0

With a function that way, you need to bind this. However, change the function to an arrow function:

prev_image = () => {
    console.log('previous image!');
}

And it should work. You no longer need to bind this, and it's also a lot cleaner.

cbll
  • 6,499
  • 26
  • 74
  • 117