Skip to content

Instantly share code, notes, and snippets.

@Zaggen
Last active April 8, 2017 04:10
Show Gist options
  • Save Zaggen/03ae797d46f38e82b2596838b782c451 to your computer and use it in GitHub Desktop.
Save Zaggen/03ae797d46f38e82b2596838b782c451 to your computer and use it in GitHub Desktop.
Flux/Redux linke store implementation experiment
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
}
}
}
@Zaggen
Copy link
Author

Zaggen commented Apr 8, 2017

GlobalStore creation:

window.globalStore = new Store({
    institution: {
    artworks: [
        {
          id: 45,
          title: 'La Mona Lisa',
          image: 'dummy2',
          artist: 'Leonardo Da Vinci',
          date: '1974'
        },
       {
         id: 345,
         title: 'Wonder Woman Making a Splash',
         image: 'dummy.jpg',
         artist: 'Leslie Lew',
         date: '1974'
       }
     ]
   }
 })

Reducer register example with globalStore

import {Store} from '../../../shared/store.class'
declare const globalStore: Store
declare const _: any

export default globalStore.registerReducer(
  'institution.artworks',
  function artworksReducer(artworks, actionType, artwork) {
    switch (actionType) {
      case 'ADD_ARTWORK':
        debugger
        return _.uniqBy(artworks.concat(artwork), 'id')
      default:
        return artworks
    }
})

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment