Kodax

مشروع عملي: تطبيق مهام — JavaScript الأساسيات

مشروع: تطبيق مهام (Todo App)

المميزات

- إضافة/حذف/تعديل المهام

- حفظ في localStorage

- تصفية حسب الحالة

- تصميم متجاوب

الهيكل

class TodoApp {
  constructor() {
    this.todos = this.loadTodos();
    this.filter = 'all';
    this.init();
  }
  
  init() {
    this.cacheDom();
    this.bindEvents();
    this.render();
  }
  
  cacheDom() {
    this.form = document.getElementById('todo-form');
    this.input = document.getElementById('todo-input');
    this.list = document.getElementById('todo-list');
    this.filters = document.querySelectorAll('[data-filter]');
  }
  
  bindEvents() {
    this.form.addEventListener('submit', e => this.handleSubmit(e));
    this.list.addEventListener('click', e => this.handleClick(e));
    this.filters.forEach(btn => {
      btn.addEventListener('click', () => {
        this.filter = btn.dataset.filter;
        this.render();
      });
    });
  }
}

إضافة مهمة

class TodoApp {
  // ... المُنشئ و saveTodos و render كما في المثال الكامل

addTodo(text) {
  const todo = {
    id: crypto.randomUUID(),  // Date.now() قد يتكرر لمهمتين في نفس الملّي ثانية
    text: text.trim(),
    completed: false,
    createdAt: new Date().toISOString()
  };
  
  this.todos.push(todo);
  this.saveTodos();
  this.render();
}
}

حذف وتبديل

class TodoApp {
  // ...

deleteTodo(id) {
  this.todos = this.todos.filter(t => t.id !== id);
  this.saveTodos();
  this.render();
}

toggleTodo(id) {
  const todo = this.todos.find(t => t.id === id);
  if (todo) {
    todo.completed = !todo.completed;
    this.saveTodos();
    this.render();
  }
}
}
// Todo App كامل
class TodoApp {
  constructor() {
    this.todos = JSON.parse(localStorage.getItem('todos')) || [];
    this.filter = 'all';
  }
  
  addTodo(text) {
    if (!text.trim()) return;
    this.todos.push({
      id: crypto.randomUUID(),  // Date.now() قد يتكرر لمهمتين أُضيفتا في نفس الملّي ثانية
      text: text.trim(),
      completed: false
    });
    this.save();
  }
  
  deleteTodo(id) {
    this.todos = this.todos.filter(t => t.id !== id);
    this.save();
  }
  
  toggleTodo(id) {
    const todo = this.todos.find(t => t.id === id);
    if (todo) todo.completed = !todo.completed;
    this.save();
  }
  
  editTodo(id, newText) {
    const todo = this.todos.find(t => t.id === id);
    if (todo) todo.text = newText;
    this.save();
  }
  
  getFiltered() {
    switch(this.filter) {
      case 'active': return this.todos.filter(t => !t.completed);
      case 'completed': return this.todos.filter(t => t.completed);
      default: return this.todos;
    }
  }
  
  save() {
    localStorage.setItem('todos', JSON.stringify(this.todos));
  }
  
  clearCompleted() {
    this.todos = this.todos.filter(t => !t.completed);
    this.save();
  }
}

// الاستخدام
const app = new TodoApp();
app.addTodo('تعلم JavaScript');
app.addTodo('بناء مشروع');
app.toggleTodo(app.todos[0].id);
console.log(app.getFiltered());
اختبر فهمك