/**
* 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}
}

版权声明:本文为MrZouJian原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。
本文链接:https://www.cnblogs.com/MrZouJian/p/8545238.html