Skip to content

Instantly share code, notes, and snippets.

@ipradev
Last active December 7, 2017 14:58
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ipradev/b260ff0850de0800a5876805ec2c70e8 to your computer and use it in GitHub Desktop.
Save ipradev/b260ff0850de0800a5876805ec2c70e8 to your computer and use it in GitHub Desktop.
class Task {
constructor(title, onDestroy) {
this.title = title;
this.isDone = false;
this.onDestroy = onDestroy || function () {};
}
render() {
this.element = document.createElement('li');
this.element.innerText = this.title;
this.element.className = this.isDone && 'done';
this.checkbox = document.createElement('input');
this.checkbox.type = 'checkbox';
this.checkbox.onchange = this.toggle.bind(this);
this.element.prepend(this.checkbox);
this.deleteButton = document.createElement('button');
this.deleteButton.type = 'button';
this.deleteButton.innerText = 'delete';
this.deleteButton.onclick = this.destroy.bind(this);
this.element.append(this.deleteButton);
return this.element;
}
toggle() {
this.isDone = !this.isDone;
this.element.className = this.isDone && 'done';
}
destroy() {
this.element.remove();
this.element = null;
this.deleteButton = null;
this.checkbox = null;
this.onDestroy(this);
}
}
class List {
constructor(container) {
this.container = container;
this.tasks = [];
}
render() {
this.element = document.createElement('ul');
this.container.append(this.element);
}
add(title) {
const task = new Task(title, this.remove.bind(this));
this.element.append(task.render());
this.tasks.push(task);
}
remove(task) {
this.tasks.splice(this.tasks.indexOf(task), 1);
}
}
const list = new List(document.getElementById('todo'));
document.getElementById('form').onsubmit = (event) => {
const el = document.getElementById('task');
list.add(el.value);
el.value = '';
el.focus();
event.preventDefault();
};
list.render();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment