33

CRUD Operations using vanilla javascript

 5 years ago
source link: https://www.tuicool.com/articles/hit/RZjMZrz
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.

Nowadays there are several javascript frameworks around such as React, Angular, Vue etc. They all offer simple and easy approach towards development of web application especially SPAs. However, many javascript learners tend to begin learning these frameworks and know little about how to similar apps in vanilla javascript.

jaQRJjb.jpg!webba6vyqz.jpg!web

One of the most basic operations in any application is CRUD(stands for Create, Read, Update, Delete). This is something we are going to achieve today. We will take a basic and good old example i.e. Todo app.

Even though vanilla JavaScript will be used for this tutorial but ES6 syntax will be used for this example instead of plain old JavaScript syntax. In order to accomplish that, babel transpiler as transpiler will be used to convert ES6/ES7 to ES5 and webpack as build tool.

I am assuming that you already have latest version of node.js on your computer. Setting up environment is going to take some extra time so no need to go into these details. Simply clone my boilerplate code from here( https://github.com/zafar-saleem/hut ) and run “npm install” to install all dependencies.

The new files will go into /src folder. So create a new file called Todo.js inside /src/scripts/ folder and write below code into that file.

euMZNbB.png!web

As you can see in above code, we are creating a class Todo and inside that class we are writing a constructor function. Even though JavaScript does not have classes by default however, ES6 has classes which is in reality a syntactic sugar on top of javascript prototype.

Now when we create a new instance of this class using new keyword, the constructor function is automatically called. That is where we will add some attributes to Todo class which we will be able to access in this entire class using keyword this .

Now that we have above code so go ahead import above file in src/index.js file and make a new instance of this class like below.

euMZNbB.png!web

Now we have some basic code in Todo.js. We also need some basic html code. Write below code in index.html file in root folder.

euMZNbB.png!web

Now that we have the basic html code. Lets go back to Todo.js and get reference to our ‘.list-item’ container. Write below code inside constructor.

euMZNbB.png!web

After getting reference to “.list-item” element, I am calling render function to render list of items on the screen. This function does not exist yet which we are going to write next.

But before writing render function we need some mock data that we are going to render. So the purpose of this tutorial we are going to use an array of objects. Write below code at the top of the Todo.js file.

euMZNbB.png!web

Now back to render function, below is the entire render function.

euMZNbB.png!web

In this function we are making sure that this.list container is empty i.e. we do not want any item to be appended to existing items. The first line simply make the container empty before appending new items.

Next we are looping mockData array that we created at the top of the Todo.js file using forEach function. Inside forEach callback function, the first this is that we are creating some DOM elements by calling createDomElements(item.id); function and we are passing current items id to that function. I will write this function next but before getting there lets finish writing this function.

Once it creates the new DOM element i.e. li element and with child elements i.e. buttons in this case, it adds that li element into to Todo class as an attribute using “this” keyword. Now we can access that li element throughout Todo class so I am accessing that li element and adding title using insertAdjacentHTML() function.

Next I am checking if current item is completed or done, if it is then I add a class to current li element which added line-through style on the item.

And finally I append that li element to this.list.

Now lets write createDomElements() function which is below.

euMZNbB.png!web

This function seems to have plenty of code but it is simple to understand. What it does is that I simply create li elements, delete, edit and complete buttons. Then I add some classes to all of these buttons and set data-id attribute and assign current item’s id that we passed as an argument from render function. Then I put text on these buttons i.e. Edit, Delete and Complete using “innerHTML”.

Finally, I append these buttons to li element which I later access in render function to perform further operation.

Now that we have the basic structure if you run npm run dev and go to localhost:2770 in the browser. You should have below items and an input field and button and four items with respective buttons.

Until you should have R part of CRUD i.e. I am reading all the elements from mockData and placing them on the screen.

Now that R part is done it is time begin working on the C part of CRUD. Write a function called create and add below code.

euMZNbB.png!web

Create function is very self explanatory, all it does it that it get the value from the text field. It creates a newItem object with attributes: ID, title, done and date.

Finally, push that newItem into mockData array and empty the textfield and call the render function to render all the items with newly created item.

Now go ahead try this in your browser. Put some text in text field. Press add button and you do not see any change. That is expected, because there is still one last part to this. Simple add an event listener to “add” button inside constructor and call create function as below.

euMZNbB.png!web

Now try it in your browser and voila. You have the new item at the bottom of the list.

Two parts of CRUD operations are completed. The next is the D part which is Delete.

For deleting item, lets write remove(delete is a reserved keyword in javascript for that reason I named it remove) function below.

euMZNbB.png!web

This function is also quite simple, first get the id from the delete button element which was added in createDomElements function using data-id attribute. Filter through mockData and place a check on current item’s id with the delete buttons id.This check simply returns all items except the item this check returns true.

After this operation re-render all the items by calling render function at the bottom.

Things looking good but hold on a minute, this function needs to be triggered by calling the delete button. As you recall or not, this button was added dynamically in “createDomElements” function. Adding events to such elements are a little tricky. Since at the time of DOM is loaded these items were not present and added later for that reason adding event listener directly to delete, update and complete buttons are not going to work.

To make this happen, add event listener to document object and find the particular button “delete” in this case to perform delete or remove operation.

euMZNbB.png!web

To call remove, self word is used. Inside the callback function this keyword loses its reference to Todo class. For that reason create a new variable called self and assign “this” keyword to it at the top of construction.

Inside the callback function, I check if the click element has a class ‘btn-delete’ i.e. is it a delete button then simply trigger the remove function and pass the event as parameter which I use inside remove function to get id of current clicked element to perform delete operation.

Update part is slightly complicated. It consists of two functions. First is to render the edit form which has text field and update button. Second, update function that performs the update operation.

euMZNbB.png!web

All above code does is to add and remove css classes to show and hide edit form which is already in the DOM with edit-popup class. Get the id from the edit button and place it on update button. Iterate through mockData and check for the current item using its id. Put the title of the item from mockData into textfield to edit.

To trigger this function, follow the same logic for delete for adding event listener. Which is below.

euMZNbB.png!web

Now its time to write update operation. Follow code below.

euMZNbB.png!web

First 2 lines of this function are to get the id of the item and value from the text field and put them in their respective variables. Then map through mockData, place a check to find the item that needs to be updated based on the id. Once that item is found, replace the title with new “itemTobeUpdate” title. Finally return that updated item from map.

Once that operation is done, hide the edit-popup form by adding and removing respective css classes. Then re-render mockData by calling render function.

To trigger this function, add below code inside constructor.

euMZNbB.png!web

Now all CRUD operations have been completed. There is one last step which is not part of CRUD but part of Todo app. That is to mark items completed. Below function will achieve this.

euMZNbB.png!web

Again follow the same pattern as rest of the functions, get the id from the button’s data-id attribute. map through mockData and find the relevant item and set its done property to true and return that item. Final step, re-render mockData by calling render function.

Again same logic to triggering delete function, add below code inside constructor to set tasks completed.

euMZNbB.png!web

Here is some basic css that is used for this tutorial. Nothing fancy.

euMZNbB.png!web

That is it for vanilla javascript CRUD operation. The next step is to covert this into an angular and react app to see the difference and find how convenient such frameworks are.

To get code and complete project clone below repository.

https://github.com/zafar-saleem/todo


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK