Skip to content

Instantly share code, notes, and snippets.

@prestonp
Last active May 29, 2018 18:01
Show Gist options
  • Save prestonp/8c17764f2a93eacafa121951ff5c0887 to your computer and use it in GitHub Desktop.
Save prestonp/8c17764f2a93eacafa121951ff5c0887 to your computer and use it in GitHub Desktop.
redux example
<html>
<body>
<button onclick="s.dispatch('increment')">increment</button>
<button onclick="s.dispatch('decrement')">decrement</button>
<button onclick="unsubscribe()">unsubscribe</button>
<div id="main"></div>
<script>
function Store(reducer) {
this.reducer = reducer;
this.listeners = [];
}
Store.prototype.getState = function() {
return this.state;
}
Store.prototype.subscribe = function(listener) {
this.listeners.push(listener);
return () => {
this.listeners = this.listeners.filter(l => l !== listener);
}
}
Store.prototype.dispatch = function(action) {
this.state = this.reducer(this.state, action);
this.listeners.forEach(listener => listener());
}
function counterReducer(state, action) {
state = state || 0;
if (action == 'increment') {
return ++state
} else if (action == 'decrement') {
return --state
}
return state
}
const s = new Store(counterReducer);
const unsubscribe = s.subscribe(() => {
const main = document.querySelectorAll('#main')[0];
main.innerText = s.getState();
});
</script>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment