antoniobennett

Antonio-Bennett

Posted on December 17, 2021

Pure JS is Hard

Hey Everyone! So this one is suuuper late and it's not Rust :(. Previous related blog is here :)

Project

So you might be wondering why did I say pure Javascript is hard...well that's because it is. Not hard in the sense of syntax and etc but when we start building complex apps that manage state etc it becomes annoying very quickly and you realize why we have frameworks. This project aims to create a todo app with pure JavaScript and eventlistener goodness.

Issue

The issue was that when a user enters tasks to do, there is no way of clearing only completed tasks.

PR

The PR can be found here if you want to just see it. First thing I did was creating a new button which only shows up with the clear task button as well.

First we add the button of course.

<a href="#" class="btn btn-sm btn-outline-danger clear-comp-tasks">Clear completed tasks</a>
Enter fullscreen mode Exit fullscreen mode

Then place inside a function that shows the button only when the task list is greater than 2

if(tasks.length > 2) {
            document.querySelector('.clear-tasks').style.display = 'inline-block';
            document.querySelector('.clear-comp-tasks').style.display = 'inline-block';
            document.querySelector('.filter-wrapper').style.display = 'block';
}
Enter fullscreen mode Exit fullscreen mode

Next is the functionality

First register the event listener to the button.

const clearCompTasks = document.querySelector(".clear-comp-tasks");
clearCompTasks.addEventListener("click", Tasklist.deleteAllCompleted);
Enter fullscreen mode Exit fullscreen mode

Then the functionality

static deleteAllCompleted(){
        if(confirm('This will delete ALL completed tasks')) {
            tasks.forEach(task => {
              if(task.status === 'completed')
              document.querySelector(`[data-id="${task.date}"]`).remove();
            });
            tasks = tasks.filter(task => task.status !== 'completed');
            localStorage.setItem('tasks', JSON.stringify(tasks));
            Tasklist.filter();
        }
}
Enter fullscreen mode Exit fullscreen mode

Overall Thoughts

I realize why everyone loves JavaScript frameworks even more now. As complexity of the app goes up, state management becomes a pain in pure js. It is still fun figuring stuff out though.

💖 💪 🙅 🚩
antoniobennett
Antonio-Bennett

Posted on December 17, 2021

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related

Hacktoberfest - PR#3
javascript Hacktoberfest - PR#3

October 22, 2022

Pure JS is Hard
javascript Pure JS is Hard

December 17, 2021

OpenSource Contribution - Live Coding
javascript OpenSource Contribution - Live Coding

April 14, 2020

Hacktoberfesting!
javascript Hacktoberfesting!

October 20, 2019