循环

初始包装:

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前端笔记, 是针对前端工程师开放的一个笔记分享平台,是前端工程师记录重点、分享经验的一个笔记本。JSRUN前端采用的 MarkDown 语法 (极客专用语法), 这里属于IT工程师。