mirror of
https://github.com/morris/vanilla-todo.git
synced 2025-08-21 13:21:29 +02:00
first commit
This commit is contained in:
67
public/scripts/TodoList.js
Normal file
67
public/scripts/TodoList.js
Normal file
@@ -0,0 +1,67 @@
|
||||
/* global VT */
|
||||
window.VT = window.VT || {};
|
||||
|
||||
VT.TodoList = function (el) {
|
||||
var state = {
|
||||
items: [],
|
||||
};
|
||||
|
||||
el.innerHTML = [
|
||||
'<div class="items"></div>',
|
||||
'<div class="todo-item-input"></div>',
|
||||
].join('\n');
|
||||
|
||||
VT.AppSortable(el.querySelector('.items'), {});
|
||||
VT.TodoItemInput(el.querySelector('.todo-item-input'));
|
||||
|
||||
el.addEventListener('sortableDrop', function (e) {
|
||||
el.dispatchEvent(
|
||||
new CustomEvent('moveItem', {
|
||||
detail: {
|
||||
item: e.detail.data.item,
|
||||
index: e.detail.index,
|
||||
},
|
||||
bubbles: true,
|
||||
})
|
||||
);
|
||||
});
|
||||
|
||||
function update(next) {
|
||||
Object.assign(state, next);
|
||||
|
||||
var container = el.querySelector('.items');
|
||||
var obsolete = new Set(container.children);
|
||||
var children = state.items.map(function (item) {
|
||||
var child = container.querySelector(
|
||||
'.todo-item[data-key="' + item.id + '"]'
|
||||
);
|
||||
|
||||
if (child) {
|
||||
obsolete.delete(child);
|
||||
} else {
|
||||
child = document.createElement('div');
|
||||
child.classList.add('todo-item');
|
||||
child.setAttribute('data-key', item.id);
|
||||
VT.TodoItem(child);
|
||||
}
|
||||
|
||||
child.todoItem.update({ item: item });
|
||||
|
||||
return child;
|
||||
});
|
||||
|
||||
obsolete.forEach(function (child) {
|
||||
container.removeChild(child);
|
||||
});
|
||||
|
||||
children.forEach(function (child, index) {
|
||||
if (child !== container.children[index]) {
|
||||
container.insertBefore(child, container.children[index]);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
el.todoList = {
|
||||
update: update,
|
||||
};
|
||||
};
|
Reference in New Issue
Block a user