I'm having trouble understanding the basic idea of Javascript event handling and variable scope. I come from Python, in which I've built a small GUI app which displays random English irregular verbs and asks the user to enter the past and participle forms. I'm trying to write the same thing in JS.
score = 0
maxQuestions = 10
function loadJSON(url, success, error) {
const xhr = new XMLHttpRequest()
xhr.open("GET", url, true)
xhr.responseType = 'json'
xhr.send()
xhr.onload = function() {
if (xhr.status == 200) {
success(xhr.response)
} else {
error(xhr)
}
}
}
/*
The JSON file looks like this:
[
[
"leap",
"leapt/leaped",
"leapt/leaped"
],
etc...
*/
function main(verbs) {
var verb = verbs.splice(Math.floor(Math.random() * verbs.length), 1)[0]
var present = verb[0]
document.getElementById('present').innerHTML = present
document.getElementById('button').addEventListener('click', function() {
check(verb)
})
}
function check(verb) {
var preterit = verb[1].split('/'),
participle = verb[2].split('/')
var user_preterit = document.getElementById('preterit').value
var user_participle = document.getElementById('participle').value
if (preterit.includes(user_preterit)) {
score += 1
}
if (participle.includes(user_participle)) {
score += 1
}
document.getElementById('score').innerHTML = score
}
function error() {
console.log('Error loading JSON file.')
}
loadJSON('js/verbs-list.json', main, error)
This works as intended, but I'm not sure how build a loop correctly in order to ask e.g. 10 questions.
I want to keep a main()
function in order to set up the event listener, have an introductory text and an option to start over, but I need to get the verb selection code into a different function that can run repeatedly without adding an event listener every time. How can I do that while keeping a reference to the verb
variable?
This was easy for me to do in Python because the app was contained in a class. I could refer to "globals" such as score, current verb and the verb list by using self
. Is it supposed to be used the same way in JS, i.e. with a class and this
, or can it be done in a simpler fashion?