redux.html 2.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798
  1. <!DOCTYPE html>
  2. <html>
  3. <head>
  4. <meta charset="utf-8">
  5. <title>Redux</title>
  6. </head>
  7. <body>
  8. <!-- <input type="text" id="tovar"> -->
  9. <select id='tovar'>
  10. <option value="пиво">пиво</option>
  11. <option value="чипсы">чипсы</option>
  12. <option value="сиги">сиги</option>
  13. </select>
  14. <input type="number" id="skok">
  15. <button id="btn">Купить</button>
  16. <script>
  17. function reducer(state, {type, ШО, СКОКА}){
  18. if (!state){
  19. return {
  20. пиво: 100,
  21. чипсы: 100,
  22. сиги: 100
  23. }
  24. }
  25. if (type === 'КУПИТЬ'){
  26. return {
  27. ...state,
  28. [ШО]: state[ШО] - СКОКА
  29. }
  30. }
  31. return state;
  32. }
  33. function createStore(reducer){
  34. let state = reducer(undefined, {})
  35. let cbs = []
  36. const getState = () => state
  37. const subscribe = cb => (cbs.push(cb),
  38. () => cbs = cbs.filter(c => c !== cb));
  39. const dispatch = action => {
  40. const newState = reducer(state, action)
  41. if (newState !== state){
  42. state = newState
  43. for (let cb of cbs) cb()
  44. }
  45. }
  46. return {
  47. getState,
  48. dispatch,
  49. subscribe
  50. }
  51. }
  52. let store=createStore(reducer);
  53. btn.onclick=function(){
  54. for(let [key] of Object.entries(store.getState())){
  55. if(tovar.value===key){
  56. store.dispatch({type: 'КУПИТЬ', ШО: tovar.value, СКОКА: skok.value});
  57. console.log(store.getState())
  58. }
  59. }
  60. }
  61. let table=document.createElement('table');
  62. for(let [key,value] of Object.entries(store.getState())){
  63. let tr=document.createElement('tr');
  64. let td=document.createElement('td');
  65. td.innerText=key+':'+value;
  66. tr.append(td);
  67. table.append(tr);
  68. }
  69. document.body.append(table);
  70. const unsubscribe=store.subscribe(()=>{
  71. while (table.hasChildNodes()) {
  72. table.removeChild(table.firstChild);
  73. }
  74. for(let [key,value] of Object.entries(store.getState())){
  75. let tr=document.createElement('tr');
  76. let td=document.createElement('td');
  77. td.innerText=key+':'+value;
  78. tr.append(td);
  79. table.append(tr);
  80. }
  81. document.body.append(table);
  82. })
  83. console.log(store.getState());
  84. </script>
  85. </body>
  86. </html>