1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74
| function createStore(reducer) { let state,listener=[]; dispatch({}); function dispatch(action) { state=reducer(state,action); listener.forEach(item=>item()); } let subscribe=(fn)=>{ listener=[...listener,fn]; return ()=>{ listener=listener.filter(item=>item!=fn); } }; let getState=()=>(JSON.parse(JSON.stringify(state))); return {dispatch,getState,subscribe} }
const TITLE_CHANGE_TEXT="title_change_text"; const TITLE_CHANGE_COLOR="title_change_color"; const CONTENT_CHANGE_TEXT="content_change_text"; let initState={ titleState:{text:"前端",color:"red"}, contentState:{text:"CSS,HTML,JS,NODE,VUE,REACT",color:"green"} }; function reducer(state=initState,action) { switch (action.type){ case TITLE_CHANGE_TEXT: return {...state,titleState:{...state.titleState,text:action.text}}; break; case TITLE_CHANGE_COLOR: return {...state,titleState:{...state.titleState,color:action.color}}; break; case CONTENT_CHANGE_TEXT: return {...state,contentState:{...state.contentState,text:action.text}}; break; }
return state; }
let store=createStore(reducer);
store.subscribe(render); let unsubscribe=store.subscribe(()=>{ console.log("KK好漂亮"); }); unsubscribe();
function Title() { let title=document.getElementById("title"); title.innerHTML=store.getState().titleState.text; title.style.color=store.getState().titleState.color; } function Content() { let content=document.getElementById("content"); content.innerHTML=store.getState().contentState.text; content.style.color=store.getState().contentState.color; } function render() { Title(); Content(); }
setTimeout(()=>{ store.dispatch({type:TITLE_CHANGE_TEXT,text:"前端其实很好玩~"}); store.dispatch({type:TITLE_CHANGE_COLOR,color:"blue"}); store.dispatch({type:CONTENT_CHANGE_TEXT,text:"html+css+js+node+vue+react"}); },3000); render();
|
Comment