Skip to content

Instantly share code, notes, and snippets.

@ahoef
Created February 23, 2016 04:37
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ahoef/e3c7a47bd123f2027909 to your computer and use it in GitHub Desktop.
Save ahoef/e3c7a47bd123f2027909 to your computer and use it in GitHub Desktop.
<!DOCTYPE html>
<head>
<script src="https://cdnjs.cloudflare.com/ajax/libs/redux/3.3.1/redux.js"></script>
<script src="https://code.jquery.com/jquery-2.2.0.min.js"></script>
</head>
<body>
Current Count: <span id="current-count"></span>
<div>
<button class="increment">+</button>
<button class="decrement">-</button>
</div>
<script>
// declare the counter reducer
function counter(state, action) {
if (typeof state === 'undefined') {
return 0;
}
switch (action.type) {
case 'INCREMENT_COUNTER':
return state + 1;
case 'DECREMENT_COUNTER':
return state - 1;
default:
return state;
}
}
// declare the render function
function render() {
$('#current-count').html(store.getState());
}
// create the store using Redux's global variable, and pass in the reducer
var createStore = Redux.createStore;
var store = createStore(counter);
// output the current state
console.log(store.getState());
// call render once to set initial state to 0
render();
// call render again, each time an action is dispatched
store.subscribe(render);
// dispatch action to increment
$('.increment').on('click', function() {
store.dispatch({type: 'INCREMENT_COUNTER'});
});
// dispatch action to decrement
$('.decrement').on('click', function() {
store.dispatch({type: 'DECREMENT_COUNTER'});
});
</script>
</body>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment