Skip to content

Instantly share code, notes, and snippets.

@Yang03
Created January 5, 2018 09:52
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Yang03/ec298ad2d6e28141cfac69ad4062c95a to your computer and use it in GitHub Desktop.
Save Yang03/ec298ad2d6e28141cfac69ad4062c95a to your computer and use it in GitHub Desktop.
redux.js
const log = (store) => (next) => (action) {
console.log('start')
next(action)
console.log('end')
}
function applayMiddleware (...middlewares) {
return (createStore) {
return (reducer, preloadedState,enhancer){
const store = new createStore(reducer, preloadedState, enhancer)
let dispath = store.dispath
let chain = []
const middlewareAPI = {
getState: store.getState,
dispath: (action) => dispath(action)
}
}
chain = middlewares.map(middleware => middleware(middlewareAPI))
dispath = chain.reduce((a,b) => (...args => a(b(...args)))(store.dispath)
return {
...store
dispath
}
}
}
function createThunkMiddleware(extraArgument) {
return ({dispath, getState}) => (next) => (action) => {
if (typeof action == 'function') {
return action(dispath, getState, extraArgument)
}
return next(action)
}
}
const thunk = createThunkMiddleware();
thunk.withExtraArgument = createThunkMiddleware
function createStore(reducer, preloadedState, enhancer ) {
let currentReducer = reducer
let currentState = preloadedState
let currentListeners = []
let nextListeners = currentListeners
let isDispacthing = false
function ensureCaneMutateNextListeners() {
if (nextListeners === currentListeners) {
nextListeners = currentListeners.slice()
}
}
function getState() {
return currentState
}
function subscribe(listener) {
if (typeof listener !== 'function') {
throw new Error('Expected listener to be a function.')
}
let isSubscribed = true
ensureCanMutateNextListeners()
nextListeners.push(listener)
return function unsubscribe() {
if (!isSubscribed) {
return
}
isSubscribed = false
ensureCanMutateNextListeners()
const index = nextListeners.indexOf(listener)
nextListeners.splice(index, 1)
}
}
function dispatch(action) {
if (isDispacthing) {
throw new Error('Reducers may not dispatch actions.')
}
isDispacthing = true
currentState = currentReducer(currentState, action)
const listeners = currentListeners = nextListeners
for (var i = 0; i < listeners.length; i++) {
const listener = listeners[i]
listener()
}
return action
}
return {
dispatch,
getState
}
}
const logReducer = (initState = {}, action) {
switch (action.type) {
case "load":
console.log(action)
break;
default:
return initState
}
}
const load = (name) => {
return {
type: 'load',
playload: name
}
}
const logAction = (name) => (dispatch, state) {
dispatch(load(name))
}
let store = applayMiddleware({thunk, api})(createStore)
store.dispatch(loadAction('haha'))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment