12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485 |
- <!DOCTYPE html>
- <html lang="en">
- <head>
- <meta charset="UTF-8" />
- <meta name="viewport" content="width=device-width, initial-scale=1.0" />
- <title>24_practic_Redux_Basket</title>
- </head>
- <body>
- <button id="A">A</button>
- <button id="B">B</button>
- <h1 id="cart"></h1>
- <script>
- function createStore(reducer) {
- let state = reducer(undefined, {});
- let cbs = [];
- function dispatch(action) {
- //if (typeof action === 'function'){
- //return action(dispatch)
- //}
- let newState = reducer(state, action);
- if (state !== newState) {
- state = newState;
- for (let cb of cbs) cb();
- }
- }
- return {
- getState() {
- return state;
- },
- dispatch,
- subscribe(cb) {
- cbs.push(cb);
- return () => {
- cbs = cbs.filter(
- (someElement) => someElement !== cb
- );
- };
- },
- };
- }
- function cartReducer(state = {}, { type, id, count }) {
- if (type === "CART_ADD") {
- return {
- ...state,
- [id]: count + (state[id] || 0),
- };
- }
- if (type === "CART_DELETE") {
- const { [id]: skip, ...newState } = state;
- return newState;
- }
- return state;
- }
- const store = createStore(cartReducer);
- store.subscribe(() => console.log(store.getState()));
- const actionCartAdd = (id, count = 1) => ({
- type: "CART_ADD",
- id,
- count,
- });
- const actionCartDelete = (id) => ({
- type: "CART_DELETE",
- id,
- });
- A.onclick = () => store.dispatch(actionCartAdd("A"));
- B.onclick = () => store.dispatch(actionCartAdd("B"));
- store.subscribe(
- () => (cart.innerText = Object.keys(store.getState()).length)
- );
- // store.dispatch(actionCartAdd("C", 4));
- // store.dispatch(actionCartDelete("B"));
- // console.log(store.getState());
- </script>
- </body>
- </html>
|