Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- let todos = [
- { id: 0, name: 'Buy milk', due: '2019-05-30', isDone: true },
- { id: 1, name: 'Buy beer', due: '2019-06-03', isDone: false },
- { id: 2, name: 'Read "The Hitchhiker\'s Guide to the Galaxy" book', due: '2019-06-14', isDone: false },
- ];
- const statics = {
- id: todos.length,
- };
- const populateTodos = (todos, container) => {
- const $div = $(container);
- $div.empty();
- todos.map(todo => {
- $div.append(todoView(todo)
- )
- });
- // Finish the function
- };
- const todoView = (todo, container) => {
- const $div = $(container);
- return (`
- <div class="todo-single">
- <input data-check-id="${todo.id}" type="checkbox" ${todo.isDone ? 'checked' : ''}/>
- <span>${todo.name} - ${moment(todo.due).format('MMMM Do YYYY')}</span>
- <button data-id="${todo.id}">X</button>
- </div>
- `);
- }
- (() => {
- // Initial populate
- populateTodos(todos, '#todos');
- // Attach events here
- // Add event
- $(document).on('click', '#btn-add', (ev) => {
- const $input = $('#todo-text');
- const $date = $('#todo-date');
- const $todo1 = { id: statics.id++, name: $input.val(), due: $date.val(), isDone: false };
- if ($date.val() === '') {
- alert('Invalid date!');
- } else {
- todos.push($todo1);
- populateTodos(todos, '#todos');
- $input.val('');
- $date.val('');
- alert('Todo Added!');
- }
- });
- // Remove event
- $(document).on('click', '[data-id]', (ev) => {
- const $target = +$(ev.currentTarget).attr('data-id');
- todos.splice(todos.findIndex(key => key.id === $target), 1);
- // statics++;
- populateTodos(todos, '#todos');
- alert('Todo Deleted!');
- });
- // Check event
- $(document).on('click', ':checkbox', (ev) => {
- const $target = +$(ev.currentTarget).attr('data-check-id');
- const index = todos.findIndex(el => el.id === $target);
- if(ev.target.checked) {
- todos[index].isDone = true;
- }else {
- todos[index].isDone = false;
- }
- alert('Todo Toggled!');
- });
- })();
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement