class TaskManager {
constructor(containerId) {
this.container = document.getElementById(containerId);
this.tasks = JSON.parse(localStorage.getItem('tasks')) || [];
this.init();
}
init() {
this.render();
this.bindEvents();
}
addTask(text) {
const task = {
id: Date.now(),
text: text,
completed: false,
createdAt: new Date().toLocaleDateString()
};
this.tasks.push(task);
this.save();
this.render();
}
toggleTask(id) {
const task = this.tasks.find(t => t.id === id);
if (task) {
task.completed = !task.completed;
this.save();
this.render();
}
}
deleteTask(id) {
this.tasks = this.tasks.filter(t => t.id !== id);
this.save();
this.render();
}
save() {
localStorage.setItem('tasks', JSON.stringify(this.tasks));
}
render() {
this.container.innerHTML = `
任务列表 (${this.tasks.length})
`;
}
}
// 使用
const taskManager = new TaskManager('taskApp');