Bind a context to the event listener (JS/TS)

Class {  var = 3  Func {
element.addEventListener("click", this.handler())
}
handler(event:Event){
console.log(this.var)
}
}

In this case, if you use the ‘this’ keyword in the listener, that works differently.

there is no more the var in the ‘this’. in the event handler, ‘this’ means ‘event.target’. So you cannot retrieve the ‘var = 3’ value. if you want, you can use the ‘bind()’ method.

Class {var = 3Func {
element.addEventListener("click", this.handler().bind(this))
}
handler(event:Event){
console.log(this.var)
}
}

And then, ‘this.var’ will work as you’d expected.

Dropout from Physics, self-taught and worked on the IT industry as a Dev/Design/Planning for 7 years. And I had run my Startup for 3 years. I fancy a ☔️ 🇬🇧

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store