1

I know this may seems silly but I'm a beginner and I just need to make sure that I understand it well:

In JavaScript when I define an event listener, the callback function is called without () to prevent immediate execution, like the below example:

document.querySelector('#button').addEventListener('click',eventHandler)

function eventHandler() {
    alert('clicked')}

my confusion is if implemented the above in a class and defined the eventHandler callback function as a method, I have to use () when I call it, like the below example:

class home {
    constructor(){
       this.button = document.querySelector('#button')
       this.clickEvent()
    }

    //events
   clickEvent(){
       //here i have to use eventHandler() not eventHandler
       this.button.addEventListener('click',()=>this.eventHandler())
    }
    //method
    eventHandler(){
        alert('clicked')
    }
   
}

new home()
Brian Tompsett - 汤莱恩
  • 5,753
  • 72
  • 57
  • 129
Ahmed Sh
  • 31
  • 3

1 Answers1

1

In code snippet with class, you are passing a function to addEventListener function which then calls the eventHandler function.

() => this.eventHandler() is an arrow function which executes this.eventHandler() inside its body

if you remove the arrow function then you will have to pass the name of the function instead of calling it

this.button.addEventListener('click', this.eventHandler)

Edit:

keep in mind that if the eventHandler method uses this, then you may run into problems because of how value of this is set in different cases.

Currently, eventHandler function isn't using this but you should read how to access correct this inside callbacks.

Yousaf
  • 27,861
  • 6
  • 44
  • 69
  • That generally isn't true, since class methods usually depend on the value of `this`, which will be lost if you just pass the function itself. (That isn't the case in this over simplified example though) – Quentin Jun 04 '20 at 08:35