You cannot select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
GHHub/src/utils/lifecycle.js

42 lines
977 B
JavaScript

const initListener = []
const authListener = []
export const addInitLinstener = (fn) => {
initListener.push(fn)
}
export const addAuthLinstener = (fn) => {
authListener.push(fn)
}
export const notifyInit = async () => {
initListener.forEach(async (fn) => {
await fn()
})
}
export const notifyAuth = async (obj) => {
authListener.forEach(async (fn) => await fn(obj))
}
// Zustand 中间件,用于订阅前端应用的生命周期,实验阶段
export const lifecycleware = (fn) => (set, get, store) => {
addInitLinstener(() => {
if (store.getState().hasOwnProperty('onInit')) {
store.getState().onInit()
} else {
console.info('store has no function: onInit.')
}
})
addAuthLinstener(() => {
if (store.getState().hasOwnProperty('onAuth')) {
store.getState().onAuth()
} else {
console.info('store has no function: onAuth.')
}
})
return fn(set, get, store)
}