Run project with docker compose
[asis23-votoe-client.git] / scripts / vote.js
blob883d8a8bf49bd3d9b510da3b9fb5d64c0a922c11
1 /**
2 * Vote module.
4 * @param object|null oRestApi
5 * @param object|null oSection
6 */
7 const Vote = (function (oRestApi, oSection) {
8 var restapi = null;
9 var section = null;
11 // Initialize REST API
12 if (oRestApi) {
13 restapi = oRestApi;
16 // Initialize section element
17 if (oSection) {
18 section = oSection;
21 /**
22 * Set REST API object.
24 * @param object|null oRestApi
26 function setRestApi(oRestApi) {
27 restapi = oRestApi;
30 /**
31 * Set section object.
33 * @param object|null oSection
35 function setSection(oSection) {
36 section = oSection;
39 /**
40 * Get admin's HTML.
42 * @return string
44 function getHtml() {
45 return `<ul></ul>`;
48 /**
49 * Load list of candidates.
51 async function loadCandidates() {
52 var ul = section.querySelector('ul');
53 var list = await restapi.getCandidates();
55 // Empty list
56 ul.innerHTML = '';
58 // Add candidates
59 for (var i = 0; i < list.length; i++) {
60 var id = list[i].id;
61 var name = list[i].name;
62 ul.innerHTML += `<li><button data-id="${id}">${name}</button></li>`;
66 /**
67 * Vote a candidate.
69 * @param object el
71 function voteCandidate(el) {
72 var id = el.dataset.id;
73 restapi.postVote(id);
76 /**
77 * Handle section events.
79 function handleEvents() {
80 section.querySelector('ul').addEventListener('click', (event) => {
81 var el = event.target;
82 if (el.matches('li button')) {
83 voteCandidate(el);
84 event.stopPropagation();
86 });
89 /**
90 * Init vote section.
92 * @param object|null oSection
94 function init(oSection) {
95 // Set section
96 if (oSection) {
97 setSection(oSection);
100 // Check section
101 if (!section) {
102 console.log("Admin section have not been set");
103 return false;
106 // Check REST API
107 if (!restapi) {
108 console.log("REST API have not been set");
109 return false;
112 // Reset section
113 section.innerHTML = getHtml();
115 // Load list of candidates
116 loadCandidates();
118 // Handle section events
119 handleEvents();
122 // Exposed functions
123 return {
124 setRestApi,
125 setSection,
126 init,