Skip to content

Instantly share code, notes, and snippets.

@park-brian
Last active August 29, 2017 03:07
Show Gist options
  • Save park-brian/56b286b68e61aa12e26d6ed9d5136499 to your computer and use it in GitHub Desktop.
Save park-brian/56b286b68e61aa12e26d6ed9d5136499 to your computer and use it in GitHub Desktop.
simple redux
<!DOCTYPE html>
<html>
<head>
<script>
window.state = {counter: 0};
const listeners = [];
const reducer = (state, action) => ({
INC: {...state, counter: state.counter + 1},
DEC: {...state, counter: state.counter - 1},
}[action.type] || state);
const dispatch = (action) => {
window.state = reducer(window.state, action);
listeners.forEach(listener => listener());
}
const subscribe = (callback) => listeners.push(callback);
const render = () => document.getElementById('counter').innerText = window.state.counter;
subscribe(render);
</script>
</head>
<body>
<span id="counter">0</span>
<button onclick="dispatch({type: 'INC'})">+</button>
<button onclick="dispatch({type: 'DEC'})">-</button>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment