Home > Blockchain >  ToDoList in JavaScript by classes
ToDoList in JavaScript by classes

Time:10-01

I wanted to train classes in Java Script with To Do List but I had some errors.

I want to make it by 4 classes (in separate files) - only for training.

  • Main.js - to coordinate rest of classes
  • AddTask.js
  • RemoveTask.js
  • SearchTask.js

I have an error with pushing tasks to toDoList in class AddTask.js.

This is code in HTML:

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Document</title>
</head>

<body>
  <h1>ToDoList</h1>
  <section>
    <input type="text">
    <button id="start">Add task</button>
  </section>
  <input type="text" >
  <h2>Number of tasks: <span>0</span></h2>
  <ul></ul>
  <script src="AddTask.js"></script>
  <script src="RemoveTask.js"></script>
  <script src="SearchTask.js"></script>
  <script src="Main.js"></script>
</body>
</html>

This is code in Main.js

class Main {
  constructor(){  
    this.addTask = new AddTask()
    this.button=document.getElementById('start')
    this.button.addEventListener('click', this.addTask.startGame.bind(this))
    this.taskNumber = document.querySelector('h2 span')
    this.ul = document.querySelector('body ul')
  }         
}
const start = new Main()

This is code in AddTask.js

class AddTask {
    
  constructor() {
    this.toDoList = []
  }
    
  startGame() {
    const input     = document.querySelector('section input')
    const titleTask = input.value;
    if (titleTask === "") return alert ('You have to write a task!');
    const task      = document.createElement('li');
    task.innerHTML  = titleTask   "<button>Delete</button>";
    this.toDoList.push(task)
    input.value     = ""
    return toDoList;
  }
}

Now the error is:

AddTask.js:14 Uncaught TypeError: Cannot read properties of undefined (reading 'push') at Main.startGame (AddTask.js:14:19).

Could you tell me what is the problem in that case?

CodePudding user response:

Remove .bind from Main Class and add this.startGame = this.startGame.bind(this); to the constructorof AddTask

class AddTask {
  constructor() {
    this.toDoList = [];
    this.startGame = this.startGame.bind(this);
  }

  startGame() {
    const input = document.querySelector("section input");
    const titleTask = input.value;
    if (titleTask === "") return alert("You have to write a task!");
    const task = document.createElement("li");
    task.innerHTML = titleTask   "<button>Delete</button>";
    this.toDoList.push(task);
    input.value = "";
    return this.toDoList;
  }
}

CodePudding user response:

So now is without error but input is not clear after click a button ("addTask"), and when I gave console.log(this.toDoList) nothing was showed at console.

  • Related