Advertisement
Guest User

Untitled

a guest
Dec 18th, 2018
67
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. function (window) {
  2.  
  3.     function Store() {
  4.         this.state = {};// estado de la aplicacion
  5.         this.reducers = {};// acciones para actualizar el estado sin mutarlo
  6.         this.subscribers = {};// componentes atentos a cambios
  7.     }
  8.    
  9.     Store.prototype.setSubscriber = function (name, subscriber) {
  10.         this.subscribers[name] = subscriber;
  11.     };
  12.  
  13.     Store.prototype.setReducer = function (name, reducer, initState = {}) {
  14.         this.state[name] = initState;
  15.         this.reducers[name] = reducer;
  16.     };
  17.  
  18.     Store.prototype.dispatch = function (action) {
  19.         var newState = {};
  20.         var reducerNames = Object.keys(this.reducers);
  21.  
  22.         reducerNames.forEach(function (reducerName) {
  23.             var currentState = this.state[reducerName];//puede ser del local storage
  24.             newState = this.reducers[reducerName](currentState, action);
  25.             this.state[reducerName] = $.extend({}, currentState, newState);
  26.         });
  27.  
  28.         var subscriberNames = Object.keys(this.subscribers);
  29.  
  30.         subscriberNames.forEach(function (subscriberName) {
  31.             var updateViewFn = this.subscribers[subscriberName];
  32.             if (updateViewFn) {
  33.                 updateViewFn(this.state, action);
  34.             }
  35.         });
  36.  
  37.     };
  38.  
  39.     window.Store = Store;
  40.  
  41. })(window);
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement