Skip to content

Instantly share code, notes, and snippets.

@jairoFernandez
Created August 4, 2018 18:21
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/a4ffeb72b813268f4ce1192b9389d30f to your computer and use it in GitHub Desktop.
Save jairoFernandez/a4ffeb72b813268f4ce1192b9389d30f to your computer and use it in GitHub Desktop.
Implementación básica de redux, sin react
<!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>Document</title>
<script src="https://cdnjs.cloudflare.com/ajax/libs/redux/4.0.0/redux.min.js"></script>
</head>
<body>
<h1>Redux fundamentos</h1>
<div>
valor: <span id="numero"></span>
<br/>
<button type="button" id="aumentar" onclick="aumentar()">Aumentar</button>
<button type="button" id="disminuir" onclick="disminuir()">Disminuir</button>
<button type="button" id="multiplicar" onclick="multiplicar()">Multiplicar</button>
</div>
<script>
// Redux game
//1. state
let state = {
cantidad: 0
}
//2. Store : reducer, state
let store = Redux.createStore(reducer, state);
//3. Reducer: función que regresa un nuevo estado
// dos params; state, action
function reducer(state, action){
let newState = Object.assign({}, state);// Regresa un nuevo estado
switch(action.type){
case "AUMENTAR":
newState.cantidad = state.cantidad + 1;
return newState;
case "DISMINUIR":
newState.cantidad = state.cantidad - 1;
return newState;
case "MULTIPLICAR":
newState.cantidad = state.cantidad * 2;
return newState;
default:
return newState;
}
}
// 4. Action: obj JS con el requisito de tener un key: "type"
// se acciona a través de un store.dispatch(action)
let actionAumentar = {
type: "AUMENTAR"
}
let actionDisminuir = {
type: "DISMINUIR"
}
let actionMultiplicar = {
type: "MULTIPLICAR"
}
// 5. Disptach ejecuta la llamada al store y pasa una accion
//store.dispatch(actionAumentar);
function aumentar(){
store.dispatch(actionAumentar);
}
function disminuir(){
store.dispatch(actionDisminuir);
}
function multiplicar(){
store.dispatch(actionMultiplicar);
}
let numero = document.getElementById("numero");
// 6. Acceder al state
let mostrarNumero = function(){
numero.innerHTML = store.getState().cantidad;
}
mostrarNumero();
// 7. Suscribirnos al state
store.subscribe(() => {
mostrarNumero();
});
</script>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment