DEV Community

loading...

Discussion on: The use for use in Svelte

Collapse
geoffrich profile image
Geoff Rich

I don't think this is a good use-case (heh) for use. It would be less code to add an event listener instead:

<script>
    function toggleInputContainer(e) {
        const input = e.target;
        if (input.value != "") {
            input.classList.add('filled');
        } else {
            input.classList.remove('filled');
        }
    }
</script>

<div class="shadow-xl p-10 bg-white max-w-xl rounded">
    <h1 class="text-4xl font-black mb-4">Login</h1>
    <div class="mb-4 relative">
        <input on:keyup={toggleInputContainer} class="input etc" id="email" type="text" >
        <label for="email" class="label etc">Email Address</label>
    </div>
    <div class="mb-4 relative">
        <input on:keyup={toggleInputContainer} class="input etc" id="password" type="password">
        <label for="password" class="label etc">Password</label>
    </div>
    <button class="removed">Submit</button>
</div>
Enter fullscreen mode Exit fullscreen mode

This way, Svelte takes care of the event listener lifecycle for you. Scenarios where you're only adding a single event listener don't need actions. If you're listening to a lot of events, then it could make sense to move the handlers into an action and dispatch a single custom event that has what you need, like in the Svelte tutorial.

Collapse
codechips profile image
Ilia Mikhailov Author

Agree. Example was mostly for demonstration purpose and is overkill, even though it's a nice one! Thanks for teaching me and others :)

Forem Open with the Forem app