24_practic_Redux_Basket.html 2.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485
  1. <!DOCTYPE html>
  2. <html lang="en">
  3. <head>
  4. <meta charset="UTF-8" />
  5. <meta name="viewport" content="width=device-width, initial-scale=1.0" />
  6. <title>24_practic_Redux_Basket</title>
  7. </head>
  8. <body>
  9. <button id="A">A</button>
  10. <button id="B">B</button>
  11. <h1 id="cart"></h1>
  12. <script>
  13. function createStore(reducer) {
  14. let state = reducer(undefined, {});
  15. let cbs = [];
  16. function dispatch(action) {
  17. //if (typeof action === 'function'){
  18. //return action(dispatch)
  19. //}
  20. let newState = reducer(state, action);
  21. if (state !== newState) {
  22. state = newState;
  23. for (let cb of cbs) cb();
  24. }
  25. }
  26. return {
  27. getState() {
  28. return state;
  29. },
  30. dispatch,
  31. subscribe(cb) {
  32. cbs.push(cb);
  33. return () => {
  34. cbs = cbs.filter(
  35. (someElement) => someElement !== cb
  36. );
  37. };
  38. },
  39. };
  40. }
  41. function cartReducer(state = {}, { type, id, count }) {
  42. if (type === "CART_ADD") {
  43. return {
  44. ...state,
  45. [id]: count + (state[id] || 0),
  46. };
  47. }
  48. if (type === "CART_DELETE") {
  49. const { [id]: skip, ...newState } = state;
  50. return newState;
  51. }
  52. return state;
  53. }
  54. const store = createStore(cartReducer);
  55. store.subscribe(() => console.log(store.getState()));
  56. const actionCartAdd = (id, count = 1) => ({
  57. type: "CART_ADD",
  58. id,
  59. count,
  60. });
  61. const actionCartDelete = (id) => ({
  62. type: "CART_DELETE",
  63. id,
  64. });
  65. A.onclick = () => store.dispatch(actionCartAdd("A"));
  66. B.onclick = () => store.dispatch(actionCartAdd("B"));
  67. store.subscribe(
  68. () => (cart.innerText = Object.keys(store.getState()).length)
  69. );
  70. // store.dispatch(actionCartAdd("C", 4));
  71. // store.dispatch(actionCartDelete("B"));
  72. // console.log(store.getState());
  73. </script>
  74. </body>
  75. </html>