ridjis
10/27/2017 - 5:39 PM

redux.js

const reduce = (state = 0, action) => {
  switch (action.type) {
     case "INCREMENT":
       return state + 1;
     case "DECREMENT":
       return state - 1;
     default:
        return state;
  }
}

const createStore = (reducer) => {
  let state;
  let listeners = [];
  
  const getState = () => state;
  
  const dispatch = (action) => {
    state = reducer(state, action);
    listeners.forEach(listener => listener());
  }
  
  const subscribe = (listener) => {
    listeners.push(listener);
    return () => {
      listeners.filter(l => l !== listener);
    }
  }
  
  dispatch({});
  
  return { getState, dispatch, subscribe };
}

const store = createStore(reduce);

const log = () => {
  console.log(store.getState());
}

store.subscribe(log);
store.dispatch({type: "INCREMENT" });
const reduce = (state = 0, action) => {
  switch (action.type) {
     case "INCREMENT":
       return state + 1;
     case "DECREMENT":
       return state - 1;
     default:
        return state;
  }
}

const createStore = (reducer) => {
  let state;
  let listeners = [];
  
  const getState = () => state;
  
  const dispatch = (action) => {
    state = reducer(state, action);
    listeners.forEach(listener => listener());
  }
  
  const subscribe = (listener) => {
    listeners.push(listener);
    return () => {
      listeners.filter(l => l !== listener);
    }
  }
  
  dispatch({});
  
  return { getState, dispatch, subscribe };
}

const store = createStore(reduce);

const render = () => {
  document.body.innerText = store.getState();
}

document.addEventListener('click', () => {
  store.dispatch({ type: "INCREMENT" });
});

render();
store.subscribe(render);