Skip to content

Instantly share code, notes, and snippets.

@amogower
Created January 12, 2017 19:13
Show Gist options
  • Select an option

  • Save amogower/4b69fa10c5c7b6b3da8fe89fea52a954 to your computer and use it in GitHub Desktop.

Select an option

Save amogower/4b69fa10c5c7b6b3da8fe89fea52a954 to your computer and use it in GitHub Desktop.
Redux Concepts (thanks @narendrashetty)
const action = {
type, // specify the action type
data // optional data can be passed
};
Store.prototype.dispatch = function(action) {
// based on the action type
// generate a new state of the application,
// by passing it to a reducer
const state = this.reducer(action);
this.state = state;
// Brodcast the new state to all subscribers
});
Store.prototype.reducer = function(action) {
// create a clone of the state
let state = Object.assign({}, this.state);
switch(action.type) {
case 'INIT':
state.data = action.data;
return state;
default:
return state;
}
};
const INITIAL_STATE = {
isLoaded: false,
data: []
};
function Store() {
this.state = INITIAL_STATE;
};
// List to hold all the subscribers
let subscribers = [];
// method used to subscribe for a state change
Store.prototype.subscribe = function(callback) {
subscribers.push(callback);
};
// This method is used to trigger all the subscribers when the state is changed
Store.prototype.triggerSubscribers = function() {
subscribers.forEach((subscriber) => {
subscriber(this.state);
});
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment