redux.html 2.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115
  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. /*zakup.onclick=function(){
  84. for(let [key] of Object.entries(store.getState())){
  85. if(tovar.value===key){
  86. store.dispatch({type: 'КУПИТЬ', ШО: tovar.value, СКОКА: skok.value});
  87. console.log(store.getState())
  88. }
  89. }
  90. }*/
  91. console.log(store.getState());
  92. </script>
  93. </body>
  94. </html>