Last active
October 15, 2018 09:43
-
-
Save jacomyal/eb3f355f15d753a30320256aba69a821 to your computer and use it in GitHub Desktop.
GIPAD intro JavaScript
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<html> | |
<head> | |
<title>Introduction au JavaScript</title> | |
</head> | |
<body> | |
<div id="root"></div> | |
<div id="form"> | |
<input type="text" id="name-input" /> | |
<button id="name-button">Add school</button> | |
</div> | |
<script> | |
let store = { | |
data: [ | |
{ sid: "0", label: "Mines" }, | |
{ sid: "1", label: "École de Design" } | |
] | |
}; | |
// Views: | |
function view(state) { | |
let dataRoot = document.createElement("ul"); | |
for (let i = 0; i < state.data.length; i++) { | |
let school = state.data[i]; | |
let domElement = document.createElement("li"); | |
domElement.innerHTML = school.label; | |
domElement.setAttribute("data-sid", school.sid); | |
dataRoot.appendChild(domElement); | |
} | |
return dataRoot; | |
} | |
// Actions: | |
function addSchool(state, newSchool) { | |
if (state.data.some(function(school) { | |
return school.sid === newSchool.sid; | |
})) { | |
console.warn("Already a school with sid ", newSchool.sid); | |
return state; | |
} else if (!newSchool.label) { | |
console.warn("New school must have a name"); | |
return state; | |
} else { | |
return { | |
...state, | |
data: state.data.concat(newSchool) | |
}; | |
} | |
} | |
function applyAction(action, param) { | |
store = action(store, param); | |
render(); | |
} | |
function render() { | |
let root = document.getElementById("root"); | |
root.innerHTML = ""; | |
root.appendChild(view(store)); | |
} | |
// Initial setup: | |
render(); | |
document | |
.getElementById("name-button") | |
.addEventListener("click", function(el) { | |
const nameInput = document.getElementById("name-input"); | |
const name = nameInput.value; | |
const newSchool = { | |
label: name, | |
sid: Math.floor(Math.random()*1000) | |
}; | |
applyAction( | |
addSchool, | |
newSchool | |
); | |
nameInput.value = ""; | |
}); | |
window.app = { | |
store, | |
render, | |
applyAction, | |
actions: { | |
addSchool | |
} | |
}; | |
</script> | |
</body> | |
</html> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment