Last active
July 7, 2016 06:22
-
-
Save madeinfree/9f1c9d42b26b0d6befcd9175933291f8 to your computer and use it in GitHub Desktop.
simple store like redux
This file contains hidden or 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
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 | |
} | |
} | |
} |
This file contains hidden or 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
const todos = (state, action) => { | |
const type = action.type | |
action['FETCH_TODOS'] = Object.assign({}, state, { todos: action.payload.todos }) | |
return action[type] | |
} | |
export { | |
todos | |
} |
This file contains hidden or 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
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