Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to code a class method which uses the object it was created in?

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 :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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))
      }
    }
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading