Sample Redux
by airroom
HTML
<script src="https://npmcdn.com/redux@latest/dist/redux.min.js"></script>
<form>
<input type="text" />
<button type="submit">Adicionar Vampiro</button>
</form>
<ul></ul>
CSS
span { cursor: pointer; }
JavaScript
let nextVampireId = 0;
const ADD_VAMPIRE = 'ADD_VAMPIRE';
const DELETE_VAMPIRE = 'DELETE_VAMPIRE';
const store = Redux.createStore(
Redux.combineReducers({
vampires: vampires
})
);
function addVampire(name) {
return {
type: ADD_VAMPIRE,
payload: {
id: nextVampireId++,
name: name
}
};
}
function deleteVampire(id) {
return {
type: DELETE_VAMPIRE,
payload: +id
};
}
function vampires(state, action) {
state = state === undefined ? [] : state;
switch (action.type) {
case ADD_VAMPIRE:
return [].concat(state, [{
id: action.payload.id,
name: action.payload.name
}]);
case DELETE_VAMPIRE:
return state.filter(vamp => vamp.id !== action.payload);
default:
return state;
}
}
function render() {
let vamps = store.getState()
.vampires
.map((el) => `${el.id} - ${el.name} <span data-id="${el.id}">X</span>`)
.join('</li><li>');
vamps = vamps.length ? `<li>${vamps}</li>` : '';
list.innerHTML = vamps;
}
const list = document.querySelector('ul');
const textField = document.querySelector('[type="text"]');
document.querySelector('form').addEventListener('submit', (e) => {
e.preventDefault();
store.dispatch(addVampire(textField.value));
textField.value = '';
render();
});
list.addEventListener('click', e => {
e.preventDefault();
if (e.target && e.target.nodeName === 'SPAN') {
store.dispatch(deleteVampire(e.target.dataset.id));
render();
}
});