Implemented Javascript into my Recipes App

I implemented some asynchronous requests on my Recipes app so the user does not have to reload the page when they do something small such as favorite a recipe or add a comment.

To allow users to favorite their recipes I hijacked the click with jquery, sent a get request to my server to get back the favorite JSON (I was able to use the nested route of recipe with the data from the link, because it was embedded in a recipe), and if the data retrieved was NULL then we know that this recipe had not been previously favorited by this user. I created a Class Object Favorite with the JSON received if it was not null, and if it was null I just added the Recipe ID we already have :

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
$.get("/recipes/" + recipeId + "/favorite.json", function(favorite) {
      if (favorite == null){
        f = new Favorite(recipeId)
      }else{
        f = new Favorite(recipeId, favorite.data.attributes["user-id"], favorite.data.id)
      }
      dom.currentTarget.children["0"].innerHTML = f.changeHeart()
      dom.currentTarget.className = f.changeClass()

      $.post("/recipes/" + recipeId + "/favorite", f)

    });

Here’s my Class Object

1
2
3
4
5
6
7
class Favorite {
  constructor(recipeId, userId, id) {
    this.recipeId = recipeId
    this.userId = userId
    this.id = id
  }
}

Once in the database, I was able to check if the favorite existed already, and either create or delete it depending on what existed already. But in the DOM I needed to update the class and picture, as well as the object in case the user toggled back and forth before a refresh, it should still work. I created two methods on the prototype to handle this:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
Favorite.prototype.changeClass = function(){
  if(this.id){
    return 'favorites favorite'
  } else {
    return 'favorites favorited'
  }
}

Favorite.prototype.changeHeart = function(){
  if(this.id){
    return '<img src="/assets/heart.png" alt="Heart">'
  } else {
    return '<img src="/assets/heart-red.png" alt="Heart">'
  }
}

And then called it on the object which was tied to a variable called c, which was set at the top of the file so it would be available globally

1
2
      dom.currentTarget.children["0"].innerHTML = f.changeHeart()
      dom.currentTarget.className = f.changeClass()

Implementing Javascript to my app has been quite the ride. Handling one small click, could take hours of time just to end up with 7 lines of code. But it makes the user experience that much better, and isn’t that who we are developing for?

Copyright Loving to Code 2025
Tech Nerd theme designed by Siteturner