官术网_书友最值得收藏!

  • JavaScript by Example
  • Dani Akash S
  • 354字
  • 2021-07-02 18:39:07

Managing task status

Inside ToDoClass, include the two new methods:

 toggleTaskStatus(index) {
this.tasks[index].isComplete = !this.tasks[index].isComplete;
this.loadTasks();
}
deleteTask(event, taskIndex) {
event.preventDefault();
this.tasks.splice(taskIndex, 1);
this.loadTasks();
}

The first method, toggleTaskStatus()is used to mark a task as completed or incomplete. It is called when a checkbox is clicked (onChange) with the index of the task, which was clicked as the parameter: 

  • Using the task's index, we assign the task's isComplete status as the negation of its current status not using the (!) operator. Hence, the completion status of the tasks can be toggled in this function.
  • Once the tasks variable is updated with new data, this.loadTasks() is called to re-render all the tasks with the updated value.

The second method, deleteTask(), is used to delete a task from the list. Currently, clicking the delete icon will take you to the root of the file system. However, before navigating you to the root of the file system, a call to toDo.deleteTask() is made with the click event and task's index as the parameters:

  • The first parameter event contains the entire event object that contains various properties and methods about the click event that just happened (try console.log(event) inside the deleteTask() function to see all the details in Chrome's console).
  • To prevent any default action (opening a URL) from happening once, we click the delete icon (the <a> tag). Initially, we need to specify event.preventDefault().
  • Then, we need to remove the task element of the array that was deleted from the tasks variable. For that, we use the splice() method, which deletes a specified number of elements from an array from a specified index. In our case, from the index of the task, which needs to be deleted, delete only a single element. This removes the task to be deleted from the tasks variable.
  • this.loadTasks() is called to re-render all the tasks with the updated value.

Refresh the page (hard reload if needed) to see how our current application works with the new code. You can now mark a task as completed and can delete a task from the list.

主站蜘蛛池模板: 正宁县| 朝阳县| 鹿泉市| 宜章县| 嘉峪关市| 灌南县| 海丰县| 蓝田县| 柞水县| 沧源| 盖州市| 怀集县| 宁强县| 府谷县| 彭州市| 临洮县| 莱芜市| 湘乡市| 集安市| 屏东县| 永仁县| 英德市| 兴城市| 乌兰县| 临高县| 乌拉特中旗| 曲阜市| 邯郸市| 龙陵县| 霍林郭勒市| 新宁县| 湘乡市| 麻阳| 龙川县| 晋州市| 靖安县| 万山特区| 古交市| 广德县| 丹巴县| 斗六市|