Last active
April 8, 2017 04:10
-
-
Save Zaggen/03ae797d46f38e82b2596838b782c451 to your computer and use it in GitHub Desktop.
Flux/Redux linke store implementation experiment
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
declare const _ | |
export class Store { | |
_reducers: {path: string, reducer: Function, id: number}[] = [] | |
__state__: any | |
_id: number | |
_subscribers = {} | |
constructor(initialState){ | |
this.__state__ = initialState | |
} | |
get(path: string, defaultVal = undefined){ | |
const val = _.at(this.__state__ , path)[0] | |
return (typeof val !== 'undefined') ? val : defaultVal | |
} | |
runReducers(actionType, data){ | |
this._reducers.forEach(({reducer, path})=> { | |
const state = this.get(path) | |
const pathSegments = path.split('.') | |
const key = pathSegments.pop() | |
// Here we replace the previous data with the new one | |
const newState = this.get(pathSegments.join('.'))[key] = reducer(state, actionType, data) | |
this.updateSubscriberState(path, newState) | |
}) | |
} | |
registerReducer(path: string, reducer){ | |
const reducerId = this._id++ | |
this._reducers.push({ | |
id: reducerId, | |
path, | |
reducer | |
}) | |
} | |
emitAction(actionType, newState){ | |
this.runReducers(actionType, newState) | |
} | |
subscribe(path, key, instance, defaultVal){ | |
this._subscribers[path] = {instance, key} | |
return this.get(path, defaultVal) | |
} | |
updateSubscriberState(path, newState){ | |
const subscriber = _.at(this._subscribers, path)[0] | |
if(subscriber){ | |
subscriber.instance[subscriber.key] = newState | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
GlobalStore creation:
Reducer register example with globalStore