Skip to content

Instantly share code, notes, and snippets.

@madeinfree
Last active July 7, 2016 06:22
Show Gist options
  • Save madeinfree/9f1c9d42b26b0d6befcd9175933291f8 to your computer and use it in GitHub Desktop.
Save madeinfree/9f1c9d42b26b0d6befcd9175933291f8 to your computer and use it in GitHub Desktop.
simple store like redux
export default class createStore {
constructor(state, actions) {
this._currentState = state
this._currentActions = actions
this._currentListener = null
return {
getState: this.getState.bind(this),
dispatch: this.dispatch.bind(this),
subscribe: this.subscribe.bind(this)
}
}
getState() {
return this._currentState
}
dispatch(action) {
this._currentState = this._currentActions(this.getState(), action)
this._currentListener()
}
subscribe(listener) {
this._currentListener = listener
return () => {
if(!this._currentListener) return
this._currentListener = null
}
}
}
const todos = (state, action) => {
const type = action.type
action['FETCH_TODOS'] = Object.assign({}, state, { todos: action.payload.todos })
return action[type]
}
export {
todos
}
import { createStore } from './createStore'
import { todos } from './todo-actions'
const ProductStore = new createStore({
todos: []
}, todos)
class TODO extends Component {
constructor(props, context) {
ProductStore.subscribe(() => {
const storeState = ProductStore.getState()
this.setState(storeState)
})
this.state = ProductStore.getState()
}
fetch_todos() {
ProductStore.dispatch({
type: 'FETCH_TODOS',
payload: {
todos: [{
name: 'foo'
}]
}
})
}
render() {
<div>
<button onClick={this.fetch_todos}>get todos</button>
<div>{ this.state.todos }</div>
</div>
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment