在下面的JS文件中,我向TODOS对象添加了2种方法(getPendingTodosCount,getPendingTodosCountFunc),一种使用箭头功能,一种不使用箭头功能。
没有箭头函数(getPendingTodosCountFunc)语法,该函数将返回正确的计数。
使用箭头功能(getPendingTodosCount),我不知道如何正确返回isSelected = 0的待办事项计数。 // this.todos.filter(f => f.isSelected == 0).length 语句将引发错误,因为它没有绑定到正确的“ this”。如何在调用函数 newTodo()时将箭头函数绑定到正确的 this ?
const classNames = {
TODO_ITEM: 'todo-container',
TODO_CHECKBOX: 'todo-checkbox',
TODO_TEXT: 'todo-text',
TODO_DELETE: 'todo-delete',
}
const list = document.getElementById('todo-list')
const itemCountSpan = document.getElementById('item-count')
const uncheckedCountSpan = document.getElementById('unchecked-count')
const TODOS={
todos:[],
getCount:()=>{
this.todos.count
},
updateSelection:function(id,selection){
this.todos.filter(f=>f.id==id).isSelected=selection;
},
getPendingTodosCount:() => {
console.log('getPendingTodosCount: '+this)
//this.todos.filter(f=>f.isSelected==0).length
},
getPendingTodosCountFunc:function(){
console.log('getPendingTodosCountFunc: '+ JSON.stringify(this))
return this.todos.filter(f=>f.isSelected==0).length
}
}
let ctr=0
function newTodo(text) {
let note=prompt('Enter to do text')
let todo={
id:++ctr,
text:note,
isSelected:0
}
TODOS.todos.push(todo)
console.log('new Todo : '+this)
console.log(TODOS.getPendingTodosCount())
console.log(TODOS.getPendingTodosCountFunc())
}
* {
box-sizing: border-box;
}
html, body {
background-color: #eee;
margin: 0;
padding: 0;
}
ul {
margin: 0;
padding: 0;
list-style-type: none;
}
.center {
align-self: center;
}
.flow-right {
display: flex;
justify-content: space-around;
}
.container {
max-width: 800px;
margin: 0 auto;
padding: 10px;
display: flex;
flex-direction: column;
background-color: white;
height: 100vh;
}
.title, .controls, .button {
flex: none;
}
.button {
padding: 10px 20px;
}
.todo-list {
flex: 1 1 0;
margin-top: 20px;
padding: 20px;
overflow-y: auto;
}
.todo-delete {
margin: 10px;
}
.todo-checkbox {
margin: 10px;
}
.todo-container {
padding: 20px;
border-bottom: 1px solid #333;
}
.todo-container:first-of-type {
border-top: 1px solid #333;
}
<!DOCTYPE html>
<html>
<head>
<title>TODO App</title>
<link rel="stylesheet" type="text/css" href="./styles.css" />
</head>
<body>
<div class="container center">
<h1 class="center title">My TODO App</h1>
<div class="flow-right controls">
<span>Item count: <span id="item-count">0</span></span>
<span>Unchecked count: <span id="unchecked-count">0</span></span>
</div>
<button class="button center" onClick="newTodo()">New TODO</button>
<ul id="todo-list" class="todo-list"></ul>
</div>
<script src="./script.js"></script>
</body>
</html>