Adding a product to the cart

To add a product to the cart, we have to click on the Add to cart button of the product panel. We need to edit ProductDiv again and implement the addToCart method.

As we said in the Introducing the UI manager section of this chapter, we would like to delegate the user interface manipulation to the UIManager class, so the addToCart method implementation is as follows:

private def addToCart() = () => UIManager.addOneProduct(product)

Indeed, we are asking UIManager to add the product to the cart. The UIManager builds a div representing the product in the cart, and if it is already in the cart, nothing happens.

The implementation is as follows:

def addOneProduct(product: Product): JQueryDeferred = {
  val quantity = 1
  def onDone = () => {
    val cartContent = cart.addProduct(CartLine(quantity, product)
                                     ).content
    $("#cartPanel").append(cartContent)
    println(s"Product $product added in the cart")
  }
  postInCart(product.code, quantity, onDone)
}

The postInCart method is called with the product code and the initial quantity of one to create a new entry in the Cart table. Once created, the onDone() method is called. This method adds the HTML elements that are needed to visualize the cart line in the user interface.

The postInCart method receives productCode, the quantity, and the method to call once the web service call is a success, as shown in the following code:

private def postInCart(productCode: String, quantity: Int, onDone: () => Unit) = {
  val url = s"${UIManager.origin}/v1/cart/products/$productCode
/quantity/$quantity" $.post(JQueryAjaxSettings.url(url)._result) .done(onDone) .fail(() => println("cannot add a product twice")) }

If the web service call is a failure, we just print the error in the browser console and nothing is added to the user interface.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset