Last active
May 29, 2018 18:01
-
-
Save prestonp/8c17764f2a93eacafa121951ff5c0887 to your computer and use it in GitHub Desktop.
redux example
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<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