|
1 | 1 | import Controller from '@ember/controller'; |
| 2 | +import {inject as service} from '@ember/service'; |
2 | 3 |
|
3 | 4 | export default Controller.extend({ |
4 | 5 | queryParams: ['questionId'], |
| 6 | + answers: [], |
| 7 | + api: service(), |
5 | 8 | actions: { |
6 | 9 | navigate(questionNumber) { |
7 | 10 | this.set('question', questionNumber) |
| 11 | + }, |
| 12 | + async selectChoice(questionNumber, choiceId) { |
| 13 | + let answers = this.answers |
| 14 | + let idx = answers.findIndex(obj => obj.id == questionNumber) |
| 15 | + if (idx > -1) { |
| 16 | + let ans = answers[idx]; |
| 17 | + //If question's entry is present then modify it |
| 18 | + const question = await this.store.findRecord('question', questionNumber) |
| 19 | + if (question.multicorrect) { |
| 20 | + if (ans.markedChoices.includes(choiceId)) { |
| 21 | + //If choice is already listed then it must have been removed |
| 22 | + let index = ans.markedChoices.indexOf(choiceId); |
| 23 | + if (index > -1) { |
| 24 | + ans.markedChoices.splice(index, 1); |
| 25 | + } |
| 26 | + } else { |
| 27 | + //Else add the choice to current marked choices |
| 28 | + ans.markedChoices = [...ans.markedChoices, choiceId] |
| 29 | + } |
| 30 | + } else { |
| 31 | + //For non-multicorrect questions, replace the previous choice |
| 32 | + ans.markedChoices = [choiceId] |
| 33 | + } |
| 34 | + } else { |
| 35 | + //No previous record of this question. Create a new entry and append to answers. |
| 36 | + answers.push({ |
| 37 | + id: questionNumber, |
| 38 | + markedChoices: [choiceId] |
| 39 | + }) |
| 40 | + } |
| 41 | + this.answers = answers |
| 42 | + }, |
| 43 | + fetchingResult: false, |
| 44 | + submitQuiz() { |
| 45 | + if (this.fetchingResult) |
| 46 | + return; |
| 47 | + let quiz = this.get('quiz') |
| 48 | + let body = { |
| 49 | + questions: this.answers |
| 50 | + } |
| 51 | + this.set('fetchingResult', true); |
| 52 | + this.api.request('/quizzes/' + quiz.id + '/submit', { |
| 53 | + method: 'POST', |
| 54 | + mode: 'cors', |
| 55 | + data: JSON.stringify(body), |
| 56 | + }).then((response) => { |
| 57 | + console.log(response) |
| 58 | + this.set('results', response) |
| 59 | + }).catch(console.error) |
| 60 | + .finally(() => { |
| 61 | + this.set('fetchingResult', false) |
| 62 | + }) |
| 63 | + |
8 | 64 | } |
9 | 65 | }, |
10 | 66 | }) |
0 commit comments