-2

I was hoping to be able to call object methods from an event listener, however, I am unable to access object properties on the called function:

import {action} from '../desktopIntegration/actions.js'

class Object {
  constructor() {
    this.property = 2
  }

  addListener() {
     action.on("keyup", this.printEvent)
  }

  printEvent() {
    console.log(this.property)
  }

}

This code gives the error:

 unable to access property of undefined

when addListener is called.

Is there a way to make this work? I want to keep the callback as a method function so that I can delete the listener on each instance of Object.

Thanks!

BradleyB19
  • 147
  • 5
  • 10

1 Answers1

0

Instance methods are not bound to the class instance by default. If a method is being used as an event listener, it is by default bound to the element emitting the event.

To fix that, you need to overwrite your method in the constructor, by a version bound to the class instance:

class Foo {
  constructor() {
    this.property = 2
    this.printEvent = this.printEvent.bind(this)
    this.addListener()
  }

  addListener() {
     document.getElementById('action').addEventListener("keyup", this.printEvent)
  }

  printEvent(event) { // added the event argument, gets automatically passed to the listener
    console.log(this.property)
    console.log(event.target.value) // to access the event emitting element, use event.target
  }

}

const bar = new Foo();
<input id="action" />

Also note that you should NEVER call your class Object.

connexo
  • 53,704
  • 14
  • 91
  • 128