Exercise 25: JavaScript - jkneal/spring-angular-train GitHub Wiki
Goals
Learn the fundamentals of JavaScript
Instructions
-
In
src/main/resources, create a new file named 'order.js'. Include this JavaScript source file insrc/main/resources/templates/shop/order.html -
In order.js, create a function named 'newOrder' that takes no arguments. This method should return an object that will be used for submitted orders. The object should provide the following:
- An 'id' property that is a random number
- A boolean property named 'submitted' that is initialized to false
- A method named 'add' that takes an argument named 'product' and an argument named 'quantity'. The product argument will be an object that contains properties: id, name, and price. The quantity will be a number but is optional. When not given default to 1. Within the add method, an order detail object should be initialized that contains the given product and quantity (used properties with the same name). Finally, all order details should be maintained in an array named 'orderDetails'. However, make sure the orderDetails variable is not accessible through the object
- A method named 'getTotal' that takes no arguments. This method should return the total price of the order. This is calculated by iterating over all the current order details, taking the price times the quantity for each detail, and summing
- A method named 'updateQuantity' that takes an argument named 'product' and an argument named 'quantity'. This should find the order detail object (if any) associated with the given product's id. Once found it should update the quantity to the new quantity
- A method named 'complete' that takes an argument named 'successCallback'. This method should first check whether the submitted property is true, and if so return an error with the message "Order has already been submitted". Otherwise it should make a POST request to the path '/orders'. It should submit JSON that includes an 'id' key equal to the order id, and a 'details' key equal to the order detail. If the POST is successful, invoke the successCallback argument as a function passing in the response. If there are errors, the method should display an alert with the message "Error in request". Finally the method should set the submitted property to true
VERIFICATION
- Start the training application and go to the app home page
- Click on the link 'Exercise 25'
- Now click the button 'Run Order Tests'. Verify you see an alert displaying the message "Order completed successfully!". If there are errors, you will see other alerts with the error message