I have this problem. I'm creating in Javascript a game similar to minefield - i decided to use a Class to generate the game levels. The Class is also in charge to generate the DOM code, including the buttons and the layout, according with the level size defined when creating the level.
Now the issue i have is that when i generate the code for each button:
box.setAttribute('onclick', this.levelName + '.checkResult(this.id)');
In the generate HTML it seems to be correct:
<button id="00" class="box" onclick="LevelOne.checkResult(this.id)">test</button>
But when i press the relative button i get this message:
Uncaught ReferenceError: LevelOne is not defined
at HTMLButtonElement.onclick (findTheSpot.html:16)
And if i do this, inserting the variable name directly in the second parameter:
box.setAttribute('onclick', 'levelOne.checkResult(this.id)');
It works perfectly.
I will paste the entire code below just to help you to visualize the entire flow - i'm totally new to javascript and i'm trying to learn as much as i can, creating different coding exercises by my own, apologies in advance for any coding horrors or rookie mistakes :D
/// creating a class to generate an array map of 0s and a single random 1
class Level {
constructor(wL, hL) {
this.widhtLevel = wL;
this.lenghtLevel = hL;
this.levelName;
this.level = [];
}
populateLevel() {
var idNumber = 0;
//Creating the main div container
var div = document.createElement('div');
div.style.width = this.widhtLevel + (this.widhtLevel * 50) + 'px';
div.style.height = this.lenghtLevel + (this.lenghtLevel * 50) + 'px';
div.setAttribute('id', 'mainContainer');
div.setAttribute('class', 'boxContainer');
document.body.appendChild(div);
for(var i = 0; i < this.lenghtLevel; i++) {
var arrayPopulation = []
for(var j = 0; j < this.widhtLevel; j++) {
arrayPopulation.push(0)
//Creating the boxes
var box = document.createElement('button');
box.textContent = "test";
box.setAttribute('id', idNumber + '' + (arrayPopulation.length - 1));
box.setAttribute('class', 'box');
box.setAttribute('onclick', this.levelName + '.checkResult(this.id)');
div.appendChild(box);
}
this.level.push(arrayPopulation);
idNumber++;
}
}
randomizeKey() {
var randomX = Math.floor(Math.random() * (this.widhtLevel - 0));
var randomY = Math.floor(Math.random() * (this.lenghtLevel - 0));
this.level[randomY][randomX] = 1;
//console.log(this.level[randomY][randomX]);
}
createLevel(name) {
this.levelName = name;
this.populateLevel()
this.randomizeKey()
for (var i = 0; i < this.level.length; i++) {
console.log(this.level[i])
}
}
var levelOne = new Level(5,5);
levelOne.createLevel("LevelOne");