Last day we built a TodoList with SvelteJS. We can add an item and cross from the list but in its current situation we cannot delete and item from the list. Today we will be making a little change to it. This change will be that we can delete the item from the list.
The Source Code for this can be found of Github.
Some Changes From The Last Day
First of all this is what both files, TodoList.svelte
and Todo.svelte
looks like now. I made little changes from the last one that I shared on the last post, like chagned variables and functions etc.
Todo.svelte
I add a new svg icon x
with an event that is triggered when we click on it, it removes the item from the list. This event is a custom event that we can create in SvelteJS to communicate with parent elemts from the child elements.
Custom Events
In Todo.svelte
we imported a function called createEventDispatcher
from the svelte library and then assigned a variable called dispatch
by calling createEventDispatcher
in it. This is then used in the removeTodo
funciton to tell the parent child to remove the item with the id
.
This way we can listen to these events in parent component and act accordingly.
TodoList.svelte
In the TodoList.svelte
we changed the addItem
function to addTodo
which pushes an object to the todos
array. In new todo we add Date.now()
as an id for it to be unique. Then there is a removeTodo
function that just filters the todos and returns a new array and removes the one that we want.
In the HTML, there is a custom event we are listening to in the <Todo/>
component which is on:remove
that we defined in the <Todo/>
which will call the removeTodo function.
I think this is all the basics that we need to start working with SvelteJS and obviously these are not the only things that are in the Svelte that we should be learning about. There are many more things to learn about in this framework like Bindings, Store, Animation and Special Elemnts etc. But for now this is okay or maybe. Anyway to learn more about SvelteJS, Check out the Tutorial & Documentation. Its your best friend.
Honestly I think it should have been only one post that sumarized all the basics of the SvelteJS but I made it into three post to take some time away from heavy stuff like Operating Systems.