您的位置:首页 > 编程语言

实现一个简单的订阅与发布模式的代码块,和redux

2018-03-11 18:25 711 查看
/**
* 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}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: