Navigation Menu

Skip to content

Instantly share code, notes, and snippets.

@jairoFernandez
Created August 4, 2018 21:32
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jairoFernandez/e90e88cf700ef907414f322ad6442875 to your computer and use it in GitHub Desktop.
Save jairoFernandez/e90e88cf700ef907414f322ad6442875 to your computer and use it in GitHub Desktop.
Implementación de un TodoApp con redux, sin reactjs
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Todo app</title>
<script src="https://cdnjs.cloudflare.com/ajax/libs/redux/4.0.0/redux.min.js"></script>
</head>
<body>
<h2>Todo app</h2>
<br/>
<label>Ingresar tarea:</label>
<input id="texto" autofocus type="text" onkeyup="agregarTarea(event)"/>
<ul id="listaDesordenada"></ul>
<script>
// Juego de redux
// 1. Crear state
let state = {
lista: []
}
// 2. Crear el store
let store = Redux.createStore(reducer, state);
// 3. Crear el reducer
function reducer(state, action){
let newState = Object.assign({}, state);
switch(action.type){
case "ADD_TODO":
// Es incorrecto porq modifica el estado
// newState.lista.push({
// id: action.id,
// tarea: action.payload,
// li: `<li>${action.payload} <button onclick='eliminarTarea(${action.id})'>Eliminar</button></li>`
// });
// return newState;
newState.lista = state.lista.concat([
{
id: action.id,
tarea: action.payload,
li: `<li>${action.payload} <button onclick='eliminarTarea(${action.id})'>Eliminar</button></li>`
}
]);
return newState;
case "DELETE_TODO":
newState.lista = newState.lista.filter((elemento)=>{
return parseInt(elemento.id) !== parseInt(action.id);
});
return newState;
default:
return newState;
}
}
// 4. Crear las acciones
// let accionAddTodo = {
// type: "ADD_TODO"
// }
let accionAddTodo = (tarea, id) => {
return {
type: "ADD_TODO",
payload: tarea,
id
}
}
let accionEliminar = (id) => {
return {
type: "DELETE_TODO",
id
}
}
// 5 Suscribirme al estado
store.subscribe(()=>{
mostrarTareas();
});
/// SECCION FUNCIONES NO REDUX
/*Funciones de la aplicación*/
let agregarTarea = (evento) => {
if(evento.keyCode === 13){
let id = ids.next().value;
store.dispatch(accionAddTodo(evento.target.value, id));
evento.target.value = "";
}
}
let mostrarTareas = ()=>{
let lista = document.getElementById("listaDesordenada");
let elementos = store.getState().lista;
let mostrarElementos = elementos.map((elemento) => {
return elemento.li;
});
lista.innerHTML = mostrarElementos;
}
let eliminarTarea = (id) => {
store.dispatch(accionEliminar(id));
}
function* hacerIds(){
let id = 1;
while(true){
yield id++;
}
}
let ids = hacerIds();
</script>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment