DEV Community

Discussion on: How State Management works? Dead simple SM in Vanilla JavaScript

Collapse
 
sgroen profile image
Viridi • Edited

Hi Vijay Pushkin,

I know this tutorial is not about the best code but I couldn't help myself from refactoring your code ;).

<!DOCTYPE html>
<html lang="en">
<head>
    <title>State Management in Vanilla JS</title>
</head>
<body>
<div id="app"></div>
<script>
  const App = {
    state: {
      count: 0,
    },
    template() {
      return `
          <h1>Hello Vanilla JS!</h1>
          <div>
            Example of state management in Vanilla JS
          </div>
          <br />
          <h1 id="counter">${this.state.count}</h1>
          <button id="button">Increase</button>
        `;
    },
    initialize(){
      document.getElementById('app').innerHTML = this.template();
      document.getElementById("button").addEventListener("click", () => App.increment());
    },
    increment() {
      this.state.count++;
      this.updateUI();
    },
    updateUI(){
      document.getElementById('counter').textContent = this.state.count;
    }
  };
  App.initialize();
</script>
</body>
</html>
Enter fullscreen mode Exit fullscreen mode
Collapse
 
jiminikiz profile image
Jiminikiz
<!DOCTYPE html>
<html lang="en">
  <head>
      <title>State Management in Vanilla JS</title>
  </head>
  <body>
    <main id="app">
    </main>
    <script id="template" type="text/template">
      <h1>{{title}}</h1>
      <h2 id="counter">{{count}}</h2>
      <button id="button">Increase</button>      
    </script>
    <script>
      const App = {
        state: {
          title: 'State Counter Example',
          count: 0,
        },
        template() {
          return template.innerHTML
            .replace('{{title}}', App.state.title)
            .replace('{{count}}', App.state.count);
        },
        initialize(){
          app.innerHTML = this.template();
          button.addEventListener("click", () => App.increment());
        },
        increment() {
          this.state.count++;
          this.render();
        },
        render(){
          counter.textContent = this.state.count;
        }
      };

      App.initialize();
    </script>
  </body>
</html>
Enter fullscreen mode Exit fullscreen mode