Maybe I’m overcomplicating, but I’m trying to write a class method which creates event listeners that fire off methods from the object they were created in.
class Example {
constructor() {
}
dosomething(){}
addListeners() {
document.addEventListener('keypress', function (e) {
if (e.key === 'Enter') {
{HERE WE NEED A REFERENCE}.dosomething()
}
})
}
}
const exampleObject = new Example()
exampleObject.addlisteners()
//*user presses Enter*
//exampleObject.dosomething() fires
>Solution :
You can use this to achieve that. Note that you need an arrow function to remain in the correct scope
class Example {
constructor() {
}
dosomething(){}
addListeners() {
document.addEventListener('keypress', (e) => {
if (e.key === 'Enter') {
this.dosomething()
}
})
}
}
const exampleObject = new Example()
exampleObject.addlisteners()
I find it a bit nicer to put the if in its own function :
class Example {
constructor() {
}
checkInput(e){
if (e.key === 'Enter') {
this.dosomething()
}
}
dosomething(){}
addListeners() {
document.addEventListener('keypress', (e) => this.checkInput(e))
}
}