minthemiddle / Countdown-With-Intention

A countdown timer with intention.
MIT License
0 stars 0 forks source link

Refactor: Extract JS to modules #10

Open minthemiddle opened 6 months ago

minthemiddle commented 6 months ago

To make the JS more maintainable, to extract the JS in modules.

minthemiddle commented 6 months ago

Follow this pattern:

<!doctype html>
<html lang="en">
    <head>
        <meta charset="UTF-8" />
        <meta name="viewport" content="width=device-width, initial-scale=1.0" />
        <title>AlpineJS App</title>
        <style>
            html,
            body {
                font-family: "Inter";
            }
            .padding {
                padding: 32px;
            }
        </style>
    </head>
    <body class="padding">
        <div id="app" x-data="one()">
            <h1 x-text="message" x-show="showMessage"></h1>
            <button @click="toggleMessage">Toggle Message</button>
        </div>

        <div x-data="two()">
            <h2>Counter: <span x-text="count"></span></h2>
            <button @click="increment">Increment</button>
            <button @click="decrement">Decrement</button>
        </div>

        <script type="module">
            import one from "./01.js";
            import two from "./02.js";

            document.addEventListener("alpine:init", () => {
                Alpine.data("one", one);
                Alpine.data("two", two);
            });
        </script>
        <script
            defer
            src="https://cdn.jsdelivr.net/npm/alpinejs@3.x.x/dist/cdn.min.js"
        ></script>
    </body>
</html>
// 01.js
export default function one() {
  return {
    message: "Hello, AlpineJS!",
    showMessage: true,
    toggleMessage() {
      this.showMessage = !this.showMessage;
    },
  };
}
// 02.js
// 02.js
export default function two() {
  return {
    count: 0,
    increment() {
      this.count++;
    },
    decrement() {
      this.count--;
    },
  };
}