DEV Community

Elisa Opalka
Elisa Opalka

Posted on

JavaScript SPA Project: Dessert Reviews

For my first JavaScript project, I made a SPA (single page application) consisting of HTML and JavaScript for the front end and a back-end API made with Ruby and Rails. One of the requirements was to use Object Oriented JavaScript (classes) to encapsulate related data and behavior. JavaScript is not a class-based object-oriented language but there are ways of using object oriented programming in it. I learned much about object oriented JavaScript when refactoring my code to include it and I would like to share that now.

Alt Text

The application only had two tables, Author and Review. The Author model only had one attribute, so I decided to only make a Review class in JavaScript. First I made a new file to keep things organized, "models/review.js". After that I needed to make a constructor method inside the class. This is a special method used to initialize objects. It is called on when an object of a class is created. In the class I can create objects that have data and function, after I define them within the class.

Alt Text

Next I needed to add functionality to my elements so I could render them. So I defined each element and assigned some attributes for styling. Next I put what I wanted into a "cardDiv" so they would all show in the "card" I got from bootstrap.

Alt Text

I made some functions to save all my elements into an array so I could call on them easier. I needed to make a create function with an argument that would refer to all of the elements when they were initialized. That is why you see "(attr)" as an argument.

Alt Text

For the rest of the class functions, it was mostly a matter of concern when deciding what to put where. I was taught that you make your best judgement call and that would be good enough. So the rest of my class has a form and completed reviews template, the ability to render the forms and reviews, a submit function, and delete function.

Alt Text

Lastly I decided to make a function to support a search bar. I found it very hard to find code that functioned similar to mine so I could get a good example of how I needed to do this. I finally found it and after setting it up.....it did not work. So I spent some time trying to implement conditional statements to get it to full functionality. It turns out, there are many different event listeners that sound similar but execute differently. In the end I needed to use the "keyup" event listener instead of "keydown". When using "keydown", it would not register the last deleted letter so it would continue to display anything with that letter in the title.

Top comments (0)