I have a syntax issue that my code editor is unable to compile. I can't seem to know what the issue is exactly. Any help would be much appreciated. This is my code:
Object.values(otherStatus).map(function(value) {
for(var i=0; i < otherStatus.length; i++) {
for(value in otherStatus[i]) {
if (otherStatus[i][value].indexOf(Todos) !==-1) {
remainingStatus.push(otherStatus[i]);
} else if (otherStatus[i][value].indexOf(Onprogress) !==-1) {
remainingStatus.push(otherStatus[i]);
} else if (otherStatus[i][value].indexOf(Done) !==-1) {
remainingStatus.push(otherStatus[i]);
} else {
remainingStatus = []
}
}
}
)};
The iteration is within another function that looks like this:
addCardtoApp = event => {
event.preventDefault();
const card = {
taskName: this.taskName.current.value,
taskDescription: this.taskDescription.current.value,
taskPeriod: this.taskPeriod.current.value,
};
const cardStatus = this.taskStatus.current.value;
let otherStatus = {
otherStatus: this.taskStatus.current.textContent.replace(`${cardStatus}`, ''),
};
let remainingStatus = []
const Todos = 'Todos'
const Onprogress = 'Onprogress'
const Done = 'Done'
Object.values(otherStatus).map(function(value) {
for(var i=0; i < otherStatus.length; i++)
for(value in otherStatus[i]) {
if (otherStatus[i][value].indexOf(Todos) !==-1) {
remainingStatus.push(otherStatus[i]);
} else if (otherStatus[i][value].indexOf(Onprogress) !==-1) {
remainingStatus.push(otherStatus[i]);
} else if (otherStatus[i][value].indexOf(Done) !==-1) {
remainingStatus.push(otherStatus[i]);
} else {
remainingStatus = []
}
}
}
)};
console.log(remainingStatus)
this.props.addCard(card, cardStatus, otherStatus);
event.currentTarget.reset();
console.log(otherStatus);
};
Related
I`m trying to remove event listener from a tile that has been filled correctly on a sudoku game. But it is not working. After i fill the correct number on slot, i wish i wouldnt be able to click it again, but happens as the GIF show, it is erasing the grayed slots, meaning that removeEventListener is not working correctly. Any Help?
function qsa(selector) {
return document.querySelectorAll(selector);
}
function removeListenTiles() {
let tiles = qsa("tile");
for (let i = 0; i < tiles.length; i++) {
if (tiles[i].innerHTML.indexOf("table") == -1) {
if (tiles[i].textContent != "") {
tiles[i].removeEventListener("click", () => handleTile(tile[i), true);
}
}
}
}
function handleTile(tile) {
if (!disableSelect) {
if (tile.classList.contains("selected")) {
removeAllGrayedSelected();
updateMove();
removeSelected(tile);
selectedTile = null;
selectedNum = null;
} else {
removeAllGrayedSelected();
if (tile.innerHTML.indexOf("table") != -1) {
for (let j = 0; j < 81; j++) {
if (qsa(".tile")[j] !== tile) removeSelected(qsa(".tile")[j]);
}
tile.classList.add("selected");
selectedTile = tile;
updateSurround(tile);
updateMove();
}
}
}
}
function addListenTile(tile) {
tile.addEventListener("click", () => handleTile(tile), true);
}
Tried the currying method,and added tile.id to handlers array. Solved the problem.
const handlers = [];
const addListenTile = (tile) => {
tile.addEventListener("click", handlers[tile.id] = handleTile(tile), true);
};
const removeListenTile = (tile) => {
tile.removeEventListener("click", handlers[tile,id], true);
}
const handleTile = function (tile) {
return function onhandlerTile(event) {
console.log("OK1")
if (!disableSelect) {
if (tile.classList.contains("selected")) {
console.log("OK2");
removeAllGrayedSelected();
updateMove();
removeSelected(tile);
selectedTile = null;
selectedNum = null;
} else {
console.log("OK3");
removeAllGrayedSelected();
if (tile.innerHTML.indexOf("table") != -1) {
for (let j = 0; j < 81; j++) {
if (qsa(".tile")[j] !== tile) removeSelected(qsa(".tile")[j]);
}
tile.classList.add("selected");
selectedTile = tile;
updateSurround(tile);
updateMove();
}
}
}
};
};
I am developing a "Battleship" game with two grids made up of divs and am currently attempting to add a click event listener to all of the divs.
The issue that I am having is that the event listener is being repeatedly triggered (until every single div has been clicked) when I refresh my page and I can't understand why...
Here's the event listener in question:
let aiGridCells = document.querySelectorAll(".ai-grid__game-cell");
aiGridCells.forEach(cell => {
cell.addEventListener("click", humanPlayer.humanAttack(cell.getAttribute('data-ai'),aiPlayer))
});
Where humanPlayer is an object that has been generated by a factory function:
const humanPlayer = playerFactory('human');
import gameboardFactory from './gameboardFactory';
const playerFactory = (name) => {
const playerBoard = gameboardFactory();
const humanAttack = (cell, player) => { // Where player is opponent
if (player.playerBoard.gameBoard[cell].id !== 'miss') {
player.playerBoard.receiveAttack(cell);
};
};
const aiAttack = (player) => { // Where player is opponent
const availableCells = [];
for (let i = 0; i < player.playerBoard.gameBoard.length; i++) {
if (player.playerBoard.gameBoard[i].id === null) {
availableCells.push(i);
};
};
const attackCell = Math.floor(Math.random() * availableCells.length);
player.playerBoard.receiveAttack(attackCell);
};
return {
name,
playerBoard,
humanAttack,
aiAttack
}
};
export default playerFactory;
and gameboardFactory is:
import shipFactory from './shipFactory';
const gameboardFactory = () => {
const gameBoard = [];
const shipYard = [];
const init = () => {
for (let i = 0; i<100; i++) {
gameBoard.push({id: null})
};
};
const checkValidCoordinates = (direction, start, end) => {
if (direction === 'horizontal') {
if ((start <= 9) && (end <= 9)) {
return true;
} else {
let newStart = (start/10).toString(10);
let newEnd = (end/10).toString(10);
if ((newStart.charAt(0)) === (newEnd.charAt(0))) {
return true;
};
};
} else {
if ((start <= 9) && (end <= 9)) {
return false
} else if (start <= 9) {
let newStart = start.toString(10);
let newEnd = end.toString(10);
if ((newStart.charAt(0)) === (newEnd.charAt(1))) {
return true;
};
} else {
let newStart = start.toString(10);
let newEnd = end.toString(10);
if ((newStart.charAt(1)) === (newEnd.charAt(1))) {
return true;
};
};
};
return false
};
const checkIfShipPresent = (direction, start, end) => {
if (direction === 'horizontal') {
for (let i = start; i <= end; i++) {
if (gameBoard[i].id !== null) {
return true;
}
};
return false;
} else {
for (let i = start; i <= end; i += 10) {
if (gameBoard[i].id !== null) {
return true;
}
};
return false;
};
};
const placeShip = (id, direction, start, end) => {
if (!checkValidCoordinates(direction, start, end)) {
return;
};
if (checkIfShipPresent(direction, start, end)) {
return;
};
const newShip = [];
if (direction === 'horizontal') {
for (let i = start; i <= end; i++) {
gameBoard[i].id = id;
newShip.push(i);
};
} else {
for (let i = start; i <= end; i += 10) {
gameBoard[i].id = id;
newShip.push(i);
};
};
shipYard.push(shipFactory(id, newShip));
};
const receiveAttack = (cell) => {
console.log(cell)
if (gameBoard[cell].id !== null) {
const attackedShip = shipYard.filter((ship) => {
return ship.id === gameBoard[cell].id;
})[0];
if (!attackedShip.hits.includes(cell)) {
attackedShip.hits.push(cell);
};
} else {
gameBoard[cell].id = 'miss';
};
};
const checkIfAllShipsSunk = () => {
let allShipsSunk = true;
shipYard.forEach((ship) => {
if (ship.isSunk() === false) {
allShipsSunk = false;
};
});
return allShipsSunk;
};
if (gameBoard.length === 0) {
init();
};
return {
gameBoard,
placeShip,
receiveAttack,
shipYard,
checkIfAllShipsSunk
};
};
export default gameboardFactory;
I'm completely lost to what the issue could be and have tried countless things to rectify it. Any suggestions would be hugely appreciated.
Thank you!
You trying to add actual function call as listener here:
let aiGridCells = document.querySelectorAll(".ai-grid__game-cell");
aiGridCells.forEach(cell => {
cell.addEventListener("click", humanPlayer.humanAttack(cell.getAttribute('data-ai'),aiPlayer))
});
So on your event listener initialization you actually call your function instead of passing it as a listener.
You can pass it like this instead:
aiGridCells.forEach(cell => {
cell.addEventListener("click", () => humanPlayer.humanAttack(cell.getAttribute('data-ai'),aiPlayer))
});
in hasValue class, why return is not working? when i try with console.log and alert, it worked.
want to implement function like priorityQueue.changePriority("Sheru", 1); changePriority class is not working.
commented code is code i tried to implement the changes i.e. i want to change the priority of existing item present in queue. Could anyone please help?
class QElement {
constructor(element, priority) {
this.element = element;
this.priority = priority;
}
}
class PriorityQueue {
constructor() {
this.items = [];
}
isEmpty() {
return this.items.length == 0;
}
add(element, priority) {
var qElement = new QElement(element, priority);
var contain = false;
for (var i = 0; i < this.items.length; i++) {
if (this.items[i].priority > qElement.priority) {
this.items.splice(i, 0, qElement);
contain = true;
break;
}
}
if (!contain) {
this.items.push(qElement);
}
}
peek() {
if (this.isEmpty())
return "No elements in Queue";
return this.items[0];
}
poll() {
if (this.isEmpty())
return "Underflow";
return this.items.shift();
}
/*changePriority(firstTerm, secondTerm)
{
let xxx = new QElement(firstTerm, secondTerm);
for (let i = 0; i < this.items.length; i++){
if (this.items[i].element === firstTerm){
this.items[i].priority = secondTerm;
this.items.splice(i, 0, xxx);
}
}
this.items.push(xxx);
}*/
hasValue(args) {
let status = false;
for (let i = 0; i < this.items.length; i++) {
if (this.items[i].element === args) {
status = true;
}
}
console.log(status);
}
size() {
if (this.isEmpty())
return "Underflow";
return this.items.length;
}
printPQueue() {
var str = "";
for (var i = 0; i < this.items.length; i++)
str += this.items[i].element + " ";
return str;
}
}
var priorityQueue = new PriorityQueue();
console.log(priorityQueue.isEmpty());
console.log(priorityQueue.peek());
priorityQueue.add("Sumit", 2);
priorityQueue.add("Gourav", 1);
priorityQueue.add("Piyush", 1);
priorityQueue.add("Sunny", 2);
priorityQueue.add("Sheru", 3);
console.log(priorityQueue.printPQueue());
console.log(priorityQueue.peek().element);
console.log(priorityQueue.poll().element);
priorityQueue.add("Sunil", 2);
console.log(priorityQueue.size());
priorityQueue.hasValue('Sumit');
console.log(priorityQueue.printPQueue());
priorityQueue.changePriority("Sheru", 1);
console.log(priorityQueue.printPQueue());
You missing return keyword. This just works:
hasValue(args) {
for (let i = 0; i < this.items.length; i++) {
if (this.items[i].element === args) {
return true;
}
}
return false;
}
I did not understand the idea how your changePriority function should work. Just find the element and move it up or down based on priority change:
swap(a, b) {
let tmp = this.items[a];
this.items[a] = this.items[b];
this.items[b] = tmp;
}
changePriority(firstTerm, secondTerm) {
let i = 0;
while (i < this.items.length) {
if (this.items[i].element === firstTerm) {
if (secondTerm < this.items[i].priority) {
// move up
this.items[i].priority = secondTerm;
while (i > 0 && this.items[i - 1].priority > secondTerm) {
this.swap(i - 1, i);
i--;
}
} else if (secondTerm > this.items[i].priority) {
// move down
this.items[i].priority = secondTerm;
while (i < this.items.length - 1 && this.items[i + 1].priority < secondTerm) {
this.swap(i + 1, i);
i++;
}
}
break;
}
i++;
}
}
I have written a class for Tic Tac Toe game. the code works fine, but i had to use object name inside class definition to call some of the methods instead of 'this' keyword. the problem occurs when method is passed as callbacks to addEventListener().
I tried to solve it by defining the the methods using arrow functions. But JS shows error "can not read property of undefined" error.
How would i overcome this situation.
here is the class implementation. you can see i used game.turnClick instead of this.turnClick
class TicTacToe{
constructor(aiPlayer,humanPlayer){
this.aiPlayer=aiPlayer;
this.humanPlayer=humanPlayer;
this.winCombos=[
[0,1,2],
[3,4,5],
[6,7,8],
[0,3,6],
[1,4,7],
[2,5,8],
[0,4,8],
[2,4,6]
];
this.originalBoard=Array.from(Array(9).keys());
this.gameWon=null;
this.cells=document.querySelectorAll('.cell');
}
startGame(){
//const cells=document.querySelectorAll('.cell');
this.cells.forEach(function(cell){
cell.innerHTML="";
cell.addEventListener('click',game.turnClick);
})
}
turnClick(e){
game.turn(e.target.id,game.humanPlayer);
if(!game.isTie()&&!game.gameWon){
window.setTimeout(function(){
game.turn(game.bestSquare(),game.aiPlayer);
game.isTie();
},1500);
}
}
turn(squareId,player){
this.originalBoard[squareId]=player;
const square=document.getElementById(squareId);
square.innerHTML=player;
document.querySelector('#click').play();
square.removeEventListener('click',game.turnClick);
this.gameWon=this.checkWin(this.originalBoard,player);
if(this.gameWon){
this.gameOver();
}
}
checkWin(board,player){
let playedSquares=[];
board.forEach(function(el,i){
if(el===player){
playedSquares.push(i);
}
})
console.log(playedSquares);
for(let [index,win] of this.winCombos.entries()){
if(win.every((el)=>{return playedSquares.includes(el)})){
return {index,player};
break;
}
}
return null;
}
gameOver(){
for(let index of this.winCombos[this.gameWon.index] ){
const square=document.getElementById(index);
square.style.backgroundColor= this.gameWon.player===this.humanPlayer?"blue":"red";
}
//const cells=document.querySelectorAll('button.cell');
this.cells.forEach(function(cell){
cell.removeEventListener('click',game.turnClick);
});
this.declareWin(this.gameWon.player===this.humanPlayer?'You Won !!! Hurray...':'You loose,AI beat you...');
}
emptySquares(){
return this.originalBoard.filter((el)=>typeof el==='number');
}
bestSquare(){
//return this.emptySquares()[0];
return this.minimax(this.originalBoard, this.aiPlayer).index;
}
isTie(){
if(this.emptySquares().length===0&& !this.gameWon){
this.cells.forEach(function(cell){
cell.style.backgroundColor='green';
cell.removeEventListener('click',game.turnClick);
});
this.declareWin(' You managed tie the game. congrats !!!');
return true;
}
else{
return false;
}
}
declareWin(msg){
if(msg.includes('won')||msg.includes('tie')){
document.querySelector('#winOrTie').play();
}
else{
document.querySelector('#lost').play();
}
document.querySelector('.endgame .message').innerText=msg;
document.querySelector('.endgame').classList.add('show');
}
minimax(newBoard,player){
let availSpots = this.emptySquares();
if (this.checkWin(newBoard, this.humanPlayer)) {
return {score: -10};
} else if (this.checkWin(newBoard, this.aiPlayer)) {
return {score: 10};
} else if (availSpots.length === 0) {
return {score: 0};
}
let moves = [];
for (let i = 0; i < availSpots.length; i++) {
let move = {};
move.index = newBoard[availSpots[i]];
newBoard[availSpots[i]] = player;
if (player === this.aiPlayer) {
let result = this.minimax(newBoard, this.humanPlayer);
move.score = result.score;
} else {
let result = this.minimax(newBoard, this.aiPlayer);
move.score = result.score;
}
newBoard[availSpots[i]] = move.index;
moves.push(move);
}
let bestMove;
if(player === this.aiPlayer) {
let bestScore = -10000;
for(let i = 0; i < moves.length; i++) {
if (moves[i].score > bestScore) {
bestScore = moves[i].score;
bestMove = i;
}
}
} else {
let bestScore = 10000;
for(let i = 0; i < moves.length; i++) {
if (moves[i].score < bestScore) {
bestScore = moves[i].score;
bestMove = i;
}
}
}
return moves[bestMove];
}
}
here is the gitHub repository containing full code
https://github.com/harikrishnan-a-k/Tic_Tac_Toe
cell.addEventListener('click',game.turnClick.bind(game));
You probably need to bind the context of your callback method to the instance.
I'm in practical JS by Gordon Zhu (wwww.watchandcode.com). I don't understand why the buttons appear in the browser/UI/client side, but for some reason, when I go to click it the button makes an animation and does nothing. You know, kind of like one of those old, old software programs some companies and job boards use.
I'm getting an
VM3950:1 Uncaught ReferenceError: todoList is not defined
at :1:1
when defining todoList by displayTodos.addTodo('first');
var todoList = {
todos: [],
displayTodos: function() {
if (this.todos.length === 0) {
console.log('Your todo list is empty!');
} else {
console.log('My todos:');
for (var i = 0; i < this.todos.length; i++) {
if (this.todos[i].completed === true) {
console.log('(x)', this.todos[i].todoText);
} else {
console.log('( )', this.todos[i].todoText);
}
}
}
},
addTodo: function(todoText) {
this.todos.push({
todoText: todoText,
completed: false
});
this.displayTodos();
},
changeTodo: function(position, todoText) {
this.todos[position].todoText = todoText;
this.displayTodos();
},
deleteTodo: function(position) {
this.todos.splice(position, 1)
this.displayTodos();
},
toggleCompleted: function(position) {
var todo = this.todos[position];
todo.completed = !todo.completed;
this.displayTodos();
},
toggleAll: function() {
var totalTodos = this.todos.length;
var completedTodos = 0;
for (var i = 0; i < totalTodos; i++) {
if (this.todos[i].completed === true) {
completedTodos++;
}
}
}
if (completedTodos === totalTodos) {
for (var i = 0; i < totalTodos; i++) {
this.todos[i].completed = false;
}
} else {
for (var i = 0; i < totalTodos; i++); {
this.todos[i].completed = true;
}
}
this.displayTodos();
}
};
var displayTodosButton = document.getElementById('displayTodosButton');
displayTodosButton.addEventListener('click', function() {
todoList.displayTodos();
});
<h1>Todo List</h1>
<button id = "displayTodosButton">Display Todos</button>
<button id = "toggleAllButton">Toggle All</button>
this keyword works different in Javascript compared in other languages, this is determined by how a function is called (runtime binding). In your handlers you may called todoList.displayTodos() or you can also update to use arrow functions, because in arrow functions, this retains the value of the enclosing lexical context's this see your code below:
var todoList = {
todos: [],
displayTodos: function() {
if (this.todos.length === 0) {
console.log('Your todo list is empty!');
} else {
console.log('My todos:');
for (var i = 0; i < this.todos.length; i++) {
if (this.todos[i].completed === true) {
console.log('(x)', this.todos[i].todoText);
} else {
console.log('( )', this.todos[i].todoText);
}
}
}
},
addTodo: function(todoText) {
this.todos.push({
todoText: todoText,
completed: false
});
this.displayTodos();
},
changeTodo: function(position, todoText) {
this.todos[position].todoText = todoText;
this.displayTodos();
},
deleteTodo: function(position) {
this.todos.splice(position, 1)
this.displayTodos();
},
toggleCompleted: function(position) {
var todo = this.todos[position];
todo.completed = !todo.completed;
this.displayTodos();
},
toggleAll: function() {
var totalTodos = this.todos.length;
var completedTodos = 0;
for (var i = 0; i < totalTodos; i++) {
if (this.todos[i].completed === true) {
completedTodos++;
}
}
if (completedTodos === totalTodos) {
for (var i = 0; i < totalTodos; i++) {
this.todos[i].completed = false;
}
} else {
for (var i = 0; i < totalTodos; i++); {
this.todos[i].completed = true;
}
}
this.displayTodos();
}
};
var displayTodosButton = document.getElementById('displayTodosButton');
var toggleAllButton = document.getElementById('toggleAllButton');
displayTodosButton.addEventListener('click', () => {
this.todoList.displayTodos();
});
toggleAllButton.addEventListener('click', () => {
this.todoList.toggleAll();
});
<h1>Todo List</h1>
<button id = "displayTodosButton">Display Todos</button>
<button id = "toggleAllButton">Toggle All</button>
The error display is : Uncaught ReferenceError: todoList is not defined
Which means exactly that when referencing the todoList object from the this context it won't be defined because the this here is your html element not the window object thus if you want to refer to your object you have to remove the this keyword that's all (The javascript this keyword has a different behavior from many other languages).
Finally if you want to read more about the this behavior in java-script you can visit : https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/this