Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Erdux - Unpredictable state container for JavaScript apps
class DecrementAction extends Error {}
class IncrementAction extends Error {}
const reducer = (state, error) => {
switch (error.constructor) {
case DecrementAction:
return state - 1
case IncrementAction:
return state + 1
default:
return state
}
}
const store = createStore(reducer, 0)
const counter = document.getElementById('counter')
store.subscribe(() => { counter.innerText = store.getState() })
const decrement = document.getElementById('decrement')
decrement.addEventListener('click', () => { throw new DecrementAction() })
const increment = document.getElementById('increment')
increment.addEventListener('click', () => { throw new IncrementAction() })
const createStore = (reducer, initialState) => {
let state = initialState
const listeners = []
window.onerror = (message, source, lineno, colno, error) => {
state = reducer(state, error)
listeners.forEach(listener => listener())
return true
}
return {
subscribe(listener) {
listeners.push(listener)
},
getState() {
return state
},
}
}
<!DOCTYPE html>
<html>
<head>
<title>Erdux - Unpredictable state container for JavaScript apps</title>
</head>
<body>
<button id="decrement">-</button>
<span id="counter">0</span>
<button id="increment">+</button>
<script src="http://cdnjs.cloudflare.com/ajax/libs/babel-core/5.8.24/browser.js"></script>
<script src="erdux.js"></script>
<script src="demo.js"></script>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment