Calling a method within another method - Javascript class object

Viewed 23

The following is my javascript code

class Sample {
   constructor() {
       this.btn = document.getElementById("btn");
       this.score_display = document.getElementById("display");
       this.current_container = document.getElementById("current_container);
       this.next_container = document.getElementById("next_container);
       this.scores = document.querySelectorAll(".scores")

       this.finalScore;   //final score 


       // Event listeners
        this.eventListeners();
    }

    eventListeners() {
        this.btn.addEventListener('click', () => {
            this.next_container.classList.remove('hidden');
            this.current_container.classList.add('hidden');
            
            this.getScores();
        });
    }

    getScores() {
       this.scores.forEach(score => {
            this. finalScore = 
            this.scores_display.innerHTML = this.score;
      });
   }
}

In the example code above, there are

  1. current container (rating app) - which has the rating/stars to be selected
  2. next container - that displays the selected rating/score from the current container
  3. When button is clicked, 'hidden' class is added to current container and removed from next.
  4. getScores() computes the scores and assigns to the finalScore
  5. Finallt, getScores() is called int he eventlistener.

The problem is, when I click btn(with eventlistener), the next_container, where the output of getScore() is to be stored, loads up very quickly before the getScore() is executed. This results in getScore() undefined.

I could manage this, by calling getScores() in the contructor so that it automatically is called, thus making a value of finalScore() available when the next_container is loaded.

How I can achieve this without the method called in the contructor

*** Edit ***

I have added the codepen link below

https://codepen.io/ajithtemp/pen/XWqzKoZ?editors=1111

1 Answers

you can call this.getScores() from the constructor, have you tried it?

constructor() {
       this.btn = document.getElementById("btn");
       this.score_display = document.getElementById("display");
       this.current_container = document.getElementById("current_container);
       this.next_container = document.getElementById("next_container);
       this.scores = document.querySelectorAll(".scores")

       this.finalScore;   //final score 


       // Event listeners
        this.eventListeners();

        this.getScores();
    }

```
Related