15_1.js 1.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253
  1. function createStoreMy(reducer) {
  2. let state = reducer({});
  3. let cbs = [];
  4. return {
  5. dispatch(actionType) {
  6. const newState = reducer(actionType, 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. // передаем функцию редьюсера
  22. let storeMy = createStoreMy(({ type }, state = true) => {
  23. if (type === "SET") return true;
  24. if (type === "RESET") return false;
  25. if (type === "TOGGLE") return !state;
  26. });
  27. storeMy.subscribe(() => console.log(storeMy.getState()));
  28. storeMy.dispatch({ type: "SET" });
  29. for (i = 0; i < 10; i++) {
  30. let ch = document.createElement("input");
  31. ch.type = "checkbox";
  32. ch.checked = storeMy.getState();
  33. let btn = document.createElement("button");
  34. btn.append("Ubsub");
  35. btn.onclick = storeMy.subscribe(() => {
  36. ch.checked = storeMy.getState();
  37. });
  38. ch.onclick = () => {
  39. storeMy.dispatch({ type: ch.checked ? "SET" : "RESET" });
  40. };
  41. document.body.append(ch);
  42. document.body.append(btn);
  43. }