/**
* Created by Mrzou on 2018/3/11.
*/
//实现简单的订阅与发布模式的代码块
export function pattern() {
let currentListeners = []
function subscribe(type, listener) {
if ((typeof listener !== ‘function‘) || (typeof listener !== ‘string‘)) {
throw new Error(‘参数类型错误‘)
} else {
currentListeners.push({type, listener})
}
}
function dispatch(type, value) {
currentListeners.forEach(v=> {
(v.type === type) && v.listener(value)
})
}
return {subscribe, dispatch}
}
//实现一个简单的redux
export function createStore(reducer) {
let currentState = {}
let currentListeners = []
function getState() {
return currentState
}
function subscribe(listener) {
currentListeners.push(listener)
}
function dispatch(action) {
currentState = reducer(currentState, action)
currentListeners.forEach(v=>v())
return action
}
dispatch({type: ‘@@MONI_REDUX/INITIALSTATE‘})
return {getState, subscribe, dispatch}
}