DEV Community

Discussion on: Vue vs Vanilla JavaScript - Beginner's Guide

Collapse
johngalt profile image
John Galt • Edited

How about this?

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Counter</title>
</head>
<body>
    <template id="counter-template">
        <div class="counter-component">
            <button class="increment-counter">+</button>
            <span class="counter">0</span>
            <button class="decrement-counter">-</button>
            <div class="inspirational-message"></div>
        </div>
    </template>
    <div id="root"></div>

    <script>
        class Counter {
            data = {
                _counter: 0,
                messages: [
                    { start: 0, end: 9, message: 'Go on with it!' },
                    { start: 10, end: 15, message: '頑張って!' },
                    { start: 16, end: 25, message: 'Sauba' },
                    { start: 26, end: 50, message: 'Good Job' },
                ]
            };

            rootEl;

            constructor() {
                let _this = this;

                var template = document.getElementById("counter-template");
                this.rootEl = template.content.cloneNode(true).children[0];
                document.querySelector("#root").appendChild(this.rootEl);


                // define properties
                Object.defineProperty(this.data, "counter", {
                    get() { return this._counter; },
                    set(value) {
                        this._counter = value;
                        _this.updateUI();
                    }
                });
                let incBtn = this.rootEl.querySelector(".increment-counter");
                incBtn.addEventListener('click', (e) => _this.increment(e));

                let decBtn = this.rootEl.querySelector(".decrement-counter");
                decBtn.addEventListener('click', (e) => _this.decrement(e));
                this.updateUI()
            }
            updateUI() {
                const count = this.data.counter;
                const { message } = this.data.messages.find(({start, end}) => count >= start && count <= end)
                this.rootEl.querySelector(".counter").innerHTML = count;
                this.rootEl.querySelector(".inspirational-message").innerText = message
            }
            increment(e) {
                if (this.data.counter < 50) {
                    this.data.counter++;
                }
            }
            decrement(e) {
                if (this.data.counter > 0) {
                    this.data.counter--
                }
            }
        }
        var pageComponents = [
            new Counter(),
            new Counter()
        ];
    </script>
</body>
</html>
Enter fullscreen mode Exit fullscreen mode