(function ToDo (activeElement) {
var storage = localStorage,
settings = {},
toDoData = {},
callbacks = {
addNewList: function (e) {
e.preventDefault();
var listName = $("#newListItem").find("[name='newListItem']").val();
toDoData[listName] = [];
updateStortage();
},
addNewItemInList: function (e) {
var listName = $(this).closest('div').data('item'),
itemName = $(this).closest('li').find("[type='text']").val();
toDoData[listName].push({name: itemName, status: 0});
updateStortage();
},
updateItemStatus: function (e) {
var attributtes = $(this).data('item').split(','),
item = toDoData[attributtes[0]][parseInt(attributtes[1])];
toDoData[attributtes[0]][parseInt(attributtes[1])].status = item.status ? 0 : 1;
updateStortage();
},
deleteItem: function (e) {
e.preventDefault();
var attributtes = $(this).data('item').split(',');
delete toDoData[attributtes[0]][parseInt(attributtes[1])];
updateStortage();
}
};
$("#newListItem").submit(callbacks.addNewList.bind(this));
$(document).on('submit', '.newItemInList', function(e){callbacks.addNewItemInList.bind(this)(e)});
$(document).on('change', '.changeStatusListItem', function(e){callbacks.updateItemStatus.bind(this)(e)});
$(document).on('click', '.deletedItem', function(e){callbacks.deleteItem.bind(this)(e)});
if (!storage.getItem('toDo'))
storage.setItem('toDo', JSON.stringify({
main: []
}))
toDoData = JSON.parse(storage.getItem('toDo'));
var listTemplate = "<div><h3></h3><ul><li><form class='newItemInList'><input type='text' required placeholder='New item'><input type='submit' value='Add new item'></form></li></ul></div>";
reRender();
function reRender() {
var t = '';
for (var i in toDoData) {
t += '<div data-item="'+i+'" >' + $(listTemplate)
.find('h3')
.text(i)
.closest('div')
.find('ul')
.append(renderItems(toDoData[i], i))
.closest('div')
.html() + '</div>';
}
function renderItems(item, listName) {
var tem = '';
item.forEach(function (v, k) {
if (v) {
tem += "<li class='"
+ (v.status ? 'completed' : '')
+"'> <input type='checkbox' "
+ (v.status ? 'checked' : '')
+" class='changeStatusListItem' data-item='"
+listName+","
+ k +"'>"
+ v.name
+ " - <a class='deletedItem' href='' data-item='"
+listName+","
+ k +"'> Delete</a> </li>";
}
})
return tem;
}
$(".to-do-lists").html(t);
}
function updateStortage() {
storage.setItem('toDo', JSON.stringify(toDoData));
reRender();
}
})($('.todo-wrap'))