15_redux.js 1.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354
  1. function createStore(reducer) {
  2. let state = reducer({});
  3. let cbs = [];
  4. return {
  5. dispatch(action) {
  6. const newState = reducer(action, state);
  7. if (newState !== state) {
  8. state = newState;
  9. cbs.forEach((cb) => cb());
  10. }
  11. },
  12. subscribe(cb) {
  13. cbs.push(cb);
  14. return () => (cbs = cbs.filter((c) => c !== cb));
  15. },
  16. getState() {
  17. return state;
  18. },
  19. };
  20. }
  21. let store = createStore(({ type }, state = true) => {
  22. if (type === "SET") return true;
  23. if (type === "RESET") return false;
  24. if (type === "TOGGLE") return !state;
  25. return state;
  26. });
  27. //console.log(store.getState())
  28. store.subscribe(() => console.log(store.getState()));
  29. store.dispatch({ type: "RESET" });
  30. store.dispatch({ type: "TOGGLE" });
  31. store.dispatch({ type: "ПИВА ДАЙ" });
  32. const actionCartSet = (id, count) => ({ type: "CART_SET", id, count });
  33. store.dispatch(actionCartSet(1, 5));
  34. function SuperCheckbox(el) {
  35. const checkbox = document.createElement("input");
  36. checkbox.type = "checkbox";
  37. checkbox.checked = store.getState();
  38. let unsubscribe = store.subscribe(
  39. () => (checkbox.checked = store.getState())
  40. );
  41. checkbox.onchange = () => store.dispatch({ type: "TOGGLE" });
  42. el.append(checkbox);
  43. }