Search code examples
javascriptprototype

Assign class method result to constructor parameter


Need to update constructor value based on the operation made on method increaseNumber. This is the original code:

function Div() {
    this.numCount = 0;
    this.increaseNumber();
    this.element = document.createElement( 'div' );   
    this.element.innerHTML = "<p class='counter'>" + this.numCount +"</p>";
  }

Div.prototype.increaseNumber = function() {
    this.numCount++;
    setTimeout(function() {
      this.increaseNumber();   
    }.bind(this), 1000);
  } 

I've tried assigning this.numCount = this.increaseNumber(), also tried placing this.increaseNumber inside value of innerHTML but nothing works.

Im getting on console the correct values, the number is increasing but I just cannot display inside divs.


Solution

  • Once you're changing the value of numCount (model), you need to update the DOM (view) with the new value ("re-render").

    Try to extract the part that assigns the value to this.element.innerHTML into a different function and call it both in the constructor and upon increaseNumber():

    function Div() {
        this.numCount = 0;
        this.element = document.createElement( 'div' );
        this.increaseNumber();
        this.renderElement();
    }
    
    Div.prototype.renderElement = function renderElement() {
        this.element.innerHTML = "<p class='counter'>" + this.numCount +"</p>";
    }
    
    Div.prototype.increaseNumber = function() {
        this.numCount++;
        setTimeout(function() {
          this.increaseNumber();   
          this.renderElement();
        }.bind(this), 1000);
    }