Last active
June 22, 2016 23:31
-
-
Save beaucharman/a4f09b123856acc40fbce1c6afd2fb58 to your computer and use it in GitHub Desktop.
Revive.js; A simple implementation of the awesome http://redux.js.org/
This file contains hidden or 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
const Revived = () => { | |
createStore = (reducer) => { | |
let state | |
let listeners = [] | |
const getState = () => state | |
const dispatch = (action) => { | |
state = reducer(state, action) | |
listeners.forEach(listener => listener()) | |
} | |
const subscribe = (listener) => { | |
listeners.push(listener) | |
return () => { | |
listeners = listeners.filter(l => l !== listener) | |
} | |
} | |
dispatch({}) | |
return { | |
getState, | |
dispatch, | |
subscribe, | |
} | |
} | |
const combineReducers = (reducers) => { | |
return (state = {}, action) => { | |
return Object.keys(reducers).reduce((nextState, key) => { | |
nextState[key] = reducers[key](state[key], action) | |
return nextState | |
}, {}) | |
} | |
} | |
return { | |
createStore, | |
combineReducers, | |
} | |
} | |
/* Usage */ | |
const { combineReducers, createStore } = Revived() | |
/* 1. Action Constants */ | |
const FOO = 'FOO' | |
const BAR = 'BAR' | |
/* 2. Action Creators */ | |
const doFoo = (data) => ({ | |
type: FOO, | |
data, | |
}) | |
const dobar = (data) => ({ | |
type: BAR, | |
data, | |
}) | |
/* 3. Reducers */ | |
const reducerOne = (state = [], action) => { | |
switch (action.type) { | |
case FOO: | |
return [ | |
...state, | |
{ | |
data: action.data, | |
} | |
] | |
default: | |
return state | |
} | |
} | |
const reducerTwo = (state = {}, action) => { | |
switch (action.type) { | |
case BAR: | |
return Object.assign({}, state, { | |
data: action.data, | |
}) | |
default: | |
return state | |
} | |
} | |
/* 4. Combine Reducers */ | |
const allReducers = combineReducers({ | |
reducerOne, | |
reducerTwo, | |
}) | |
/* 5. Create Store */ | |
const store = createStore(allReducers) | |
/* 6. Action Dispatchers */ | |
const dispatchDoFoo = (data) => store.dispatch(doFoo(data)) | |
const dispatchDoBar = (data) => store.dispatch(doBar(data)) | |
/* Example implementation */ | |
const elements = document.getElementsByClassName('item') | |
Array.prototype.forEach.call(elements, (element) => { | |
element.addEventListener('click', (e) => { | |
dispatchDoFoo(e.target.innerText) | |
console.log(store.getState()) | |
}) | |
}) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment