1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798 |
- <!DOCTYPE html>
- <html>
- <head>
- <meta charset="utf-8">
- <title>Redux</title>
- </head>
- <body>
- <!-- <input type="text" id="tovar"> -->
- <select id='tovar'>
- <option value="пиво">пиво</option>
- <option value="чипсы">чипсы</option>
- <option value="сиги">сиги</option>
- </select>
- <input type="number" id="skok">
- <button id="btn">Купить</button>
- <script>
- function reducer(state, {type, ШО, СКОКА}){
- if (!state){
- return {
- пиво: 100,
- чипсы: 100,
- сиги: 100
- }
- }
- if (type === 'КУПИТЬ'){
- return {
- ...state,
- [ШО]: state[ШО] - СКОКА
- }
- }
- return state;
- }
- function createStore(reducer){
- let state = reducer(undefined, {})
- let cbs = []
-
- const getState = () => state
- const subscribe = cb => (cbs.push(cb),
- () => cbs = cbs.filter(c => c !== cb));
- const dispatch = action => {
- const newState = reducer(state, action)
- if (newState !== state){
- state = newState
- for (let cb of cbs) cb()
- }
- }
-
- return {
- getState,
- dispatch,
- subscribe
- }
- }
-
- let store=createStore(reducer);
- btn.onclick=function(){
- for(let [key] of Object.entries(store.getState())){
- if(tovar.value===key){
- store.dispatch({type: 'КУПИТЬ', ШО: tovar.value, СКОКА: skok.value});
- console.log(store.getState())
- }
- }
- }
- let table=document.createElement('table');
- for(let [key,value] of Object.entries(store.getState())){
- let tr=document.createElement('tr');
- let td=document.createElement('td');
- td.innerText=key+':'+value;
- tr.append(td);
- table.append(tr);
- }
- document.body.append(table);
-
- const unsubscribe=store.subscribe(()=>{
- while (table.hasChildNodes()) {
- table.removeChild(table.firstChild);
- }
- for(let [key,value] of Object.entries(store.getState())){
- let tr=document.createElement('tr');
- let td=document.createElement('td');
- td.innerText=key+':'+value;
- tr.append(td);
- table.append(tr);
- }
- document.body.append(table);
- })
- console.log(store.getState());
- </script>
- </body>
- </html>
|