//-----------------------------------------------------------------------------
//假設(shè) 存在一個核心操作 接收參數(shù)coreArg
//建立洋蔥模型,包裹N層中間件
//要求:
// 在核心代碼執(zhí)行執(zhí)之前必須要有序執(zhí)行中間件
// 核心代碼執(zhí)行后層層返回
// 每個中間件都能接收到coreArg
function receiveMiddleware () {
//拿到中間件隊列
let middlewareList = Array.prototype.slice.call(arguments);
//將中間件隊列改造為函數(shù)層層嵌套形式
//[a,b,c,d] => a(b(c(d(core)))) By reduce
let tiggerPip = middlewareList.reduce((a, b) => (core) => a(b(core)));
let tiggerPipWitchCoreHandler = tiggerPip(() => { console.log('我是核心操作') });
return tiggerPipWitchCoreHandler;
}
const middleware1 = (next) => (lastMDarg) => {
console.log('lm 1 start')
next(lastMDarg);
console.log('lm 1 end')
};
const middleware2 = (next) => (lastMDarg) => {
console.log('lm 2 start')
next(lastMDarg);
console.log('lm 2 end')
};
const middleware3 = (next) => (lastMDarg) => {
console.log('lm 3 start')
next(lastMDarg);
console.log('lm 3 end')
};
let dispatch = receiveMiddleware(middleware1, middleware2, middleware3);
dispatch({ type: 'fff' });
//-----------------------------------------------------------------------------
//增加異步操作
const store = {
status: {name: 'zhangsan'},
getState: () => { return this.status },
dispatch: (arg) => {console.log(`我是核心操作,參數(shù)=${arg}`)}
};
function receiveMiddleware () {
//拿到中間件隊列
let middlewareList = Array.prototype.slice.call(arguments);
let dispatch = store.dispatch;
let middlewareAPI = {
dispatch: (arg) => { dispatch(arg) },
getState: store.getState,
};
//判斷中間件數(shù)量
if (middlewareList.length === 0) { return dispatch }
//將核心操作當(dāng)作參數(shù)賦予每個中間件
middlewareList = middlewareList.map((middleware) => middleware(middlewareAPI));
//將中間件隊列改造為函數(shù)層層嵌套形式
//[a,b,c,d] => a(b(c(d(core)))) By reduce
let tiggerPip = middlewareList.reduce((a, b) => (reallyDispatch) => a(b(reallyDispatch)));
//重寫dispatch
dispatch = tiggerPip(store.dispatch);
return dispatch;
}
const middleware1 = (middlewareAPI) => (next) => (lastMDarg) => {
console.log('lm 1 start')
next(lastMDarg);
console.log('lm 1 end')
};
const middleware2 = (middlewareAPI) => (next) => (lastMDarg) => {
console.log('lm 2 start')
next(lastMDarg);
console.log('lm 2 end')
};
const middleware3 = (middlewareAPI) => (next) => (lastMDarg) => {
console.log('lm 3 start')
next(lastMDarg);
console.log('lm 3 end')
};
const supportAsyncMiddleware = (middlewareAPI) => (next) => (lastMDarg) => {
console.log('lm supportAsyncMiddleware start')
if (typeof lastMDarg === 'function') {
lastMDarg(middlewareAPI)
} else {
next(lastMDarg);
console.log('lm supportAsyncMiddleware end')
}
};
let dispatch = receiveMiddleware(middleware1,
middleware2,
middleware3,
supportAsyncMiddleware);
let asyncFun = (middlewareAPI) => {
setTimeout(() => {
let mockGetData = 'im mock data'
middlewareAPI.dispatch(mockGetData)
console.log(middlewareAPI.getState())
}, 3000)
}
dispatch(asyncFun)
最后編輯于 :
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者