SOURCE

console 命令行工具 X clear

                    
>
console
function todo(state = [], action = {}) {
    switch (action.type) {
        case 'add':
            return [...state, action.payload]
        case 'remove':
            return state.filter(item => item !== action.payload)
        default:
            return state
    }
}


function createStore(reducer,initState) {
    let state = reducer()
    const listeners = []

    function getState() {
        return state
    }

    function subscribe(listener) {
        listeners.push(listener)
    }

    function dispatch(action) {
        state = reducer(state, action)
        listeners.forEach(listener => {
            if (typeof listener === 'function') {
                listener()
            }
        })
    }

    return {
        getState,
        subscribe,
        dispatch
    }
}

const store = Redux.createStore(todo)

const todoListEl = document.getElementById('todoList')

todoListEl.addEventListener('click', (e) => {
    if (e.target.tagName === 'BUTTON') {
        const todo = e.target.getAttribute('data-todo')
        store.dispatch({ type: 'remove', payload: todo })
    }
})

function render() {
    const todoList = store.getState()
    const content = todoList.reduce((res, item) => {
        return res += `<li><span  style='width:200px;display:flex;justify-content:space-between;'>${item} <button data-todo=${item}>×</button></span></li/>`
    }, ``)
    todoListEl.innerHTML = content
}

render()

store.subscribe(render)
console.log('store', Object.keys(store))

const todoEl = document.getElementById('todo')

const addBtn = document.getElementById('add')

addBtn.addEventListener('click', () => {
    const payload =  todoEl.value
    const todoList = store.getState()
    if(!payload) return alert('请输入待办名称')
    if(todoList.includes(payload)) return alert('名称重复!')
    store.dispatch({ type: 'add',payload:todoEl.value })
    todoEl.value = ''
})

const testBtn = document.getElementById('test')

testBtn.addEventListener('click', () => {
    const todoList = store.getState()
    todoList.length = 1
})
<div>
	<ol id="todoList">
	</ol>
	<input id="todo" placeholder="请输入待办名称"/>
    <button id="add">添加</button>
    <button id="test">测试</button>
</div>

本项目引用的自定义外部资源