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
Collapse
 
dapone profile image
Afisunlu Dapo • Edited

"app" in "app.innerHTML" has no reference, even though the code works perfectly. Can you please enlighten me? Pardon me me for being a novice. I was expecting something like app = document,getElementById("app")

Thread Thread
 
jiminikiz profile image
Jiminikiz

Hey Afisunlu, totally a valid question:

Both app and template exist because each DOM node that has a defined id attribute gets added to the global window object and therefore is able to be referenced without explicit initialization. This is part of the reason why id attributes should be unique for each DOM node in the tree.

Try it with another DOM node and a different id!