home.js 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475
  1. export default {
  2. rendered: false,
  3. workoutList: document.getElementById("workoutList"),
  4. render: function(newWorkout){
  5. if(!this.rendered){
  6. this.getWorkouts();
  7. this.buttons();
  8. this.rendered = true;
  9. }
  10. if(newWorkout) this.addWorkout(newWorkout);
  11. },
  12. buttons: function(){
  13. document.getElementById("homeLogout").addEventListener("click", ()=>{
  14. fetch("/user/logout")
  15. .then(r=>r.json())
  16. .then((response)=>{
  17. if(response.error){
  18. notify("error", response.error.message);
  19. }else{
  20. changePage("login");
  21. }
  22. })
  23. .catch((err)=>{
  24. notify("error", "Something went wrong, try refreshing the page");
  25. });
  26. });
  27. document.getElementById("homeNewWorkout").addEventListener("click", ()=>{
  28. changePage("newWorkout");
  29. });
  30. },
  31. getWorkouts: function(){
  32. fetch("/workout", {
  33. method: "get",
  34. headers: {
  35. "Content-Type": "application/json"
  36. }
  37. })
  38. .then(r=>r.json())
  39. .then((response)=>{
  40. if(response.error){
  41. notify("error", response.error.message);
  42. }else{
  43. this.renderWorkouts(response);
  44. }
  45. })
  46. .catch((err)=>{
  47. notify("error", "ERROR: Unable to retrieve workouts");
  48. });
  49. },
  50. renderWorkouts: function(workouts){
  51. while(this.workoutList.children.length > 0){
  52. this.workoutList.removeChild(this.workoutList.firstChild);
  53. }
  54. for(let i = 0; i < workouts.length; i++){
  55. this.addWorkout(workouts[i]);
  56. }
  57. },
  58. addWorkout: function(workout){
  59. const button = document.createElement("button");
  60. button.classList.add("button");
  61. button.textContent = workout.name;
  62. button.addEventListener("click", ()=>{
  63. changePage("session", workout);
  64. });
  65. this.workoutList.appendChild(button);
  66. }
  67. }