Search code examples
constructorweb-componentonloadlit-elementlit

lit: no attributes values in constructor


I'm building a count down in lit, and there is no HTML attributes (count, width, color, colorback, display) values unless adding timeout to constructor:

JS:

import {LitElement, html} from 'lit';

class ProgressBar extends LitElement
{ 
  static get properties()
  {
    return {
      count:      {type: Number},
      width:      {type: Number},
      color:      {type: String},
      colorback:  {type: String},
      display:    {type: String}
    }
  }  

  render()
  {
    let output = '';
    if(this.display==='true')
    {
      output = html`
      <style>
      :host > div
      {
        background-color: ${this.colorback};
        width: 100%;
      }
      :host > div > div
      {
        background-color: ${this.color};
        width: ${this.width}%;
        height: 30px;
      }            
      </style>
      <div>
        <div></div>
      </div>
    `;
    }
    return output;
  }

  draw()
  {
    let self = this
    
    let x = self._date_end - (+new Date());
    self.width = x * 100 / self.count

    if(self.width>0)
    {
      window.setTimeout(function()
      {
        self.draw()
      }, 1000 / 60)
    }
    else
      self.width = 0
  }

  main()
  {
    let self        = this
    self._date_end  = new Date((+new Date())+self.count);
    self.draw()
  }

  constructor()
  {
    super()
    let self = this
    // working
    window.setTimeout(function()
    {
      self.main()
    }, 1000)
    // not working
    self.main()
  }   
}

window.customElements.define('progress-bar', ProgressBar)

HTML:

<!DOCTYPE html>
<html>
    <head>
    </head>
    <body>
        <progress-bar
            display="true"
            width="100"
            color="#4cAf50"
            colorback="#ddd"
            count="5000">
        </progress-bar>
        <script src="main.js"></script>
    </body>
</html>

How to deal with it? Thank you


Solution

  • Using connectedCallback method works fine:

    connectedCallback()
    {
        super.connectedCallback()        
        this.main()
    }
    
    constructor()
    {
        super()
    }  
    

    https://lit.dev/docs/components/lifecycle/#connectedcallback