I am just beginning to learn JavaScript and although I feel I am starting to grasp the language, I don't feel I know how to structure an app properly. I decided to start small and build a "TODO"-app using a modular pattern.
I am aware that I should use more validations, there are unused functions, and there may be a missing semicolon here and there. My main focus on this thing was to see if I could structure an app in a good way.
I would love some feedback on my setup. Is this a proper way to set up such a small application? Am I missing something completely? Am I using the modular pattern correctly?
Generally, have I gotten the gist of it?
(function todoApp() {
var storage = (function () {
var _db,
todos,
addTodo,
removeTodo,
updateTodo,
getAllTodos,
save;
if (!window.localStorage.todoApp) {
window.localStorage.todoApp = JSON.stringify({todos: []});
}
_db = JSON.parse(window.localStorage.todoApp);
addTodo = function addTodo(todo) {
var id = Date.now().toString();
_db.todos.push({id: id, todo: todo});
save();
};
removeTodo = function removeTodo(id) {
_db.todos.every(function (c, i) {
if (c.hasOwnProperty("id") && c.id == id) {
_db.todos.splice(i, 1);
save();
return false;
}
});
};
updateTodo = function updateTodo(id, todo) {
_db.todos.every(function (c, i) {
if (c.hasOwnProperty("id") && c.id == id) {
_db.todos[i].todo = todo;
save();
return false;
}
});
};
getAllTodos = function getAllTodos() {
return _db.todos;
};
save = function save() {
window.localStorage.todoApp = JSON.stringify(_db);
};
return {
addTodo: addTodo,
removeTodo: removeTodo,
updateTodo: updateTodo,
getAllTodos: getAllTodos
};
})();
var view = (function (storage) {
var $todos = $("[rel='jstodo-container'] > [rel='jstodo-todos']"),
todos = storage.getAllTodos(),
render;
render = function render() {
$todos.html("");
todos.forEach(function (c) {
$todos.append("<li rel='" + c.id + "'>" + c.todo + "</li>");
});
};
return {
render: render
};
})(storage);
view.render();
$("[rel='jstodo-container'] > [rel='jstodo-submit']").on("click", function () {
storage.addTodo($("[rel='jstodo-container'] > [rel='jstodo-input']").val());
view.render();
});
})();
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width">
<script src="https://code.jquery.com/jquery-3.1.1.min.js" integrity="sha256-hVVnYaiADRTO2PzUGmuLJr8BLUSjGIZsDYGmIJLv2b8=" crossorigin="anonymous"></script>
<title>JS Bin</title>
</head>
<body>
<div rel="jstodo-container">
<h1>Todos: </h1>
<input type="text" rel="jstodo-input"/>
<button rel="jstodo-submit">Legg til!</button>
<ul rel="jstodo-todos"></ul>
</div>
</body>
</html>
Here is a jsbin of the project (in case the Stack Snippet has permission issues).