循环

初始包装:

let action = addTodo('TODO')

const dispatchAndLog = (store, action) => {
  log('before', action)
  store.dispatch(action)
  log('finish', store.getStatus())
}

每次调用自己定义的dispatchAndLog,麻烦,直接替换原来的dispatch:

let originDispatch = store.dispatch;
store.dispatch = (store, action) => {
  log('before', action)
  originDispatch(action)
  log('finish', store.getStatus())
}

多个middleware时,每个都会替换dispatch,并且允许修改store对象不好

const doSomethingBefore = (msg) => console.log(msg)
const doSomethingAfter = (msg) => console.info('done', msg)

let store = {
  dispatch() {
    console.log('dispatch')
  }
}

const Log = (next) => (action) => {
  doSomethingBefore(action);
  let result = next(action);
  doSomethingAfter(action);
  return result;
}

const Filter = (next) => (action) => {
  doSomethingBefore(action);
  let result = next(action);
  doSomethingAfter(action);
  return result;
}

let applyMiddleware = (store) => (...middlewares) => {
  middlewares = middlewares.reverse();
  middlewares.forEach((middleware) => {
    store.dispatch = middleware(store.dispatch);
  })
}

applyMiddleware(store)(Log, Filter)

store.dispatch('wtf')
/*
  wtf
  wtf
  dispatch
  done wtf
  done wtf
*/
JSRUN notes