I am learning to code by making a todo app in pure javascript. My first attempt can be seen here: conquerjs.com/todo
It's all cosmetic, meaning it stores no information, generates no objects or arrays, though it was sure fun to learn how to manipulate DOM elements in pure javascript and building my first "program"!
I am rebuilding it in a more OOP manner. In this first Jsfiddle: https://jsfiddle.net/zv6ohr9b/
when(toDo, "keypress", function(event){
if (event.key == "Enter" || event.keyCode == 13) {
pushArray();
toDo.value = "";
}
});
function pushArray(){
var nt = new Task(toDo.value, "No note yet");
fruits.push(nt);
var task = document.createElement("div");
task.setAttribute("class", "taskitem");
task.innerHTML = nt.Name;
var t = document.createElement("input");
t.setAttribute("class", "tasknote");
task.appendChild(t);
when(t, "keypress", function(event){
if (event.key == "Enter" || event.keyCode == 13) {
nt.Note = t.value;
this.parentNode.innerHTML = nt.Name + " " + nt.Note;
t.value = "";
}
});
result.appendChild(task);
console.log(fruits);
}
hitting enter fires a function that does everything. creates a new task object, pushes it to the array, displays the task and appends a note that can be updated anytime, for example - task:get milk note:almond milk. However I eventually want to rebuild this app again using local storage, and again with ajax and JSON. I'm thinking I'm going to have a hard time injecting that functionality into this single function without breaking it. So I did it again and broke the steps down into several smaller functions that 'plug' into each other: https://jsfiddle.net/8wm0r345/
function Task(name, note) {
this.Note = note;
this.Name = name;
this.completed = false;
}
function pushArray() {
var nt = new Task(toDo.value, "No note yet");
taskArray.push(nt);
displayArray(result, nt.Name);
appendNote(result, nt);
}
function displayArray(x, obj) {
var task = make("div", "class", "taskitem", obj);
x.appendChild(task);
}
function appendNote(el, obj) {
var t = make("input", "class", "tasknote");
el.appendChild(t);
when(t, "keypress", submitNote.bind(null, obj, t));
}
function submitNote(newTask, theInput) {
if (event.key == "Enter" || event.keyCode == 13) {
newTask.Note = theInput.value;
var n = make("div", "class", "hasNote", newTask.Note);
var t = theInput;
t.parentNode.insertBefore(n, t.nextSibling);
t.parentNode.removeChild(t);
when(n, "dblclick", function() {
n.parentNode.insertBefore(t, n.nextSibling);
n.parentNode.removeChild(n);
});
}
}
My question is: What is the recommended approach to building a small program like this? And are there any alarming issues in either code presented here? Thank you.